Reputation: 330
DataFrame:
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Event':[0,1,2,3],
'Cost':[10000, 5000, 15000, 2000]})
Dictionary:
dict = {'Music' : 0, 'Poetry' : 1, 'Theatre' : 2, 'Comedy' : 3}
If I want to map based on dictionary keys, I use:
df['new_column']= df['Event'].map(dict)
Is there a way I can map dictionary values, instead of keys?
Upvotes: 2
Views: 547
Reputation: 24322
use dict comprehension+map()
:
dct= {'Music' : 0, 'Poetry' : 1, 'Theatre' : 2, 'Comedy' : 3}
df['new_column']=df['Event'].map({v:k for k,v in dct.items()})
OR
Another way via replace()
:
df['new_column']=df['Event'].replace(dct.values(),dct.keys())
output of df
:
Date Event Cost new_column
0 10/2/2011 0 10000 Music
1 11/2/2011 1 5000 Poetry
2 12/2/2011 2 15000 Theatre
3 13/2/2011 3 2000 Comedy
Note: Don't assign anything to dict
function in python
Upvotes: 2