繁体   English   中英

使用字典向 pandas dataframe 添加一列

[英]adding a column to a pandas dataframe using a dictionary

我想根据字典向现有的 dataframe 添加列。 如果我的 dataframe 看起来像:

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

我的字典看起来像:

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

然后,我试图得到一个 dataframe 看起来像:

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

使用DataFrame.assign**解包字典:

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

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

您也可以通过以下方式执行此操作:-

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

一种方法是使用pd.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

您可以在字典键值对上运行循环并将它们添加到您的 dataframe。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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