Skip to content
Advertisement

How can I map tuple key with df values updating an existing column?

I am trying to map a column of my df with a dictionary. My dictionary contains tuple as key and I want to update an existing column value based on the key. How can I achieve that ?

sample df

JavaScript

sample dict

JavaScript

final df

JavaScript

Advertisement

Answer

Create Series with MultiIndex by keys, convert columns in same order like keys by DataFrame.set_index and then use Series.update:

JavaScript

EDIT: If there is multple columns:

JavaScript

EDIT1: If set name in Series s, is possible only set MultiIndex:

JavaScript

This solution overwrite existing values in col1, if need replace missing values NaN or Nones use:

JavaScript

First solution set 1:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement