简体   繁体   中英

Create a new column in data frame from a dict

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM