Skip to content
Advertisement

Create pandas series using a dictionary as mapper

Is there a built-in function to create a pandas.Series column using a dictionary as mapper and index levels in the data frame ?

The idea is to create a new column based on values in index levels and a dictionary. For instance:

Let’s suppose the following data frame, where id, name and code and different levels in indexes

JavaScript

and the following dictionary d = {'a': {'y', 'z'}, 'b': {'x'}}

The output of the new column should look like:

JavaScript

As a result of mapping in which new = 1 if code index value was in the dictionary list of values with key name, 0 otherwise.

I was trying to manually make this mapping but I am not sure how to iterate over index levels.

This is my attempt so far:

JavaScript

But I am getting the following error which makes me thing that I am not iterating the index levels properly or as expected in conjunction with the dictionary.

JavaScript

Any suggestion?

Advertisement

Answer

Use this for the new column you need:

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