简体   繁体   中英

adding a column to a pandas dataframe using a dictionary

I want to add columns to an existing dataframe based on a dictionary. If my dataframe looks like:

import pandas as pd
column_names=['name','surname','age']
lfa=[("tom","jones",44),("elvis","prestley",50),("jim","reeves",30)]
lfa=pd.DataFrame(lfa,columns=column_names)
lfa

and my dictionary looks like:

new_cols= {"adj1":"adjustment1","adj2":"adjustment2"}

then, I am trying to get a dataframe that looks like:

column_names=['name','surname','age','adj1','adj2']
lfa=[("tom","jones",44,"adjustment1","adjustment2"), 
("elvis","prestley",50,"adjustment1","adjustment2"), 
("jim","reeves",30,"adjustment1","adjustment2")]
lfa=pd.DataFrame(lfa,columns=column_names)
lfa

Use DataFrame.assign with unpack dict by ** :

df = lfa.assign(**new_cols)
print (df)
    name   surname  age         adj1         adj2
0    tom     jones   44  adjustment1  adjustment2
1  elvis  prestley   50  adjustment1  adjustment2
2    jim    reeves   30  adjustment1  adjustment2

Or DataFrame.join :

df = lfa.join(pd.DataFrame(new_cols, index=lfa.index))
print (df)
    name   surname  age         adj1         adj2
0    tom     jones   44  adjustment1  adjustment2
1  elvis  prestley   50  adjustment1  adjustment2
2    jim    reeves   30  adjustment1  adjustment2

You can also do this by:-

lfa[list(new_cols.keys())]=new_cols.values()

print(lfa)
    name    surname     age     adj1        adj2
0   tom     jones       44  adjustment1     adjustment2
1   elvis   prestley    50  adjustment1     adjustment2
2   jim     reeves      30  adjustment1     adjustment2

One way could be usingpd.concat :

In [533]: df = pd.concat([lfa, pd.DataFrame(new_cols, index=lfa.index)], 1)

In [534]: df
Out[534]: 
    name   surname  age         adj1         adj2
0    tom     jones   44  adjustment1  adjustment2
1  elvis  prestley   50  adjustment1  adjustment2
2    jim    reeves   30  adjustment1  adjustment2

You can run a loop on dictionary key-value pairs and add them to you dataframe.

for key,value in new_cols.items():
    lfa[key] = value

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