Reputation: 4241
I have a Pandas df:
a b c
0 'k' 2 4
1 'l' 3 7
2 'm' 0 -3
3 'n' 4 4
I have a dict: {'k': 'kilo', 'l': 'lima', 'm': 'mike', 'n': 'november'}
How can I create a new column in my df across those keys from the dict:
a b c new
0 'k' 2 4 'kilo'
1 'l' 3 7 'lima'
2 'm' 0 -3 'mike'
3 'n' 4 4 'november'
Thank you.
Upvotes: 0
Views: 118
Reputation: 393863
Just call map
and pass the dict, this will perform a lookup of your series values against the values in your dict, this is vectorised and will be much faster than doing this in a loop:
In [26]:
t = {'k': 'kilo', 'l': 'lima', 'm': 'mike', 'n': 'november'}
df['new'] = df['a'].map(t)
df
Out[26]:
a b c new
0 k 2 4 kilo
1 l 3 7 lima
2 m 0 -3 mike
3 n 4 4 november
I notice that in your data you have quote marks around your data, in which case the above won't work because your dict keys are just a single character so you would need to define your dict with quote marks also for the keys:
In [28]:
t = {"'k'": 'kilo', "'l'": 'lima', "'m'": 'mike', "'n'": 'november'}
df['new'] = df['a'].map(t)
df
Out[28]:
a b c new
0 'k' 2 4 kilo
1 'l' 3 7 lima
2 'm' 0 -3 mike
3 'n' 4 4 november
however, I would just remove the quote marks if they are unnecessary:
In [30]:
df['a'] = df['a'].str.replace("'", '')
df['a']
Out[30]:
0 k
1 l
2 m
3 n
Name: a, dtype: object
Upvotes: 5