Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including columns using MAP and dictionary in a dataframe

I am trying to include a column in a dataframe. I am using MAP tool in order to add it because it should be referenced to one variable.

Here is the current dataframe:

  X      Y            Z
  xx    high         10
        slow         20
        fat          30
  xy    high         15
        slow         10
        fast         30

I would like to include a column D taking X as a reference. This new column should be based on a dict (dictionary) with the following values:

{'xx': -4.50, 'xy': -10.21}

So I did:

df['D'] = df['X'].map(dicc)

However, when I run the code a message appears KeyError: 'X' . Am I missing something in the code or it is an issue in the data type (str / float)?

Any help would be appreciated. Thanks a lot!

EDIT: I get the dataframe from a groupby taking Xand Y as reference (thanks for the comment).

like image 440
Newbie Avatar asked Jul 18 '26 12:07

Newbie


1 Answers

You can use a simple list comprehension to do it

df = pd.DataFrame({'X':['xx', 'xx', 'xx', 'xy', 'xy', 'xy'], 
                   'Y':['high', 'slow', 'fat']*2, 
                   'Z':[10, 20, 30, 15, 10, 30]})

dicc = {'xx': -4.5, 'xy':-10.21}

df['D'] = [dicc[i] for i in df['X']]

e Extra:If your df comes from a grouby and the code says an error because it can't find column 'X', it's because 'X' is now an index column. To fix that just say df = df.reset_index() to get your DF to look like the one in this answer.

like image 152
JPS BOOKS Avatar answered Jul 20 '26 03:07

JPS BOOKS