如何基于 pandas 中的列合并两个数据框 [英] how to merge two dataframes based on a column in pandas
本文介绍了如何基于 pandas 中的列合并两个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数据帧,
df1=pd.DataFrame({"Req":["Req 1","Req 2","Req 3"],"Count":[1,2,1]})
Req Count
0 Req 1 1
1 Req 2 2
2 Req 3 1
df2 = pd.DataFrame({ Req: [需求1,需求2],计数:[0,1]})
Req Count
0 Req 1 0
1 Req 2 1
我正在尝试根据要求列合并这些df
I am trying to merge these df's based on "Req" column
我想要的输出是
Req total from_1 from_2
Req 1 1 1 0
Req 2 3 2 1
Req 3 1 1 0
我尝试了 pd.merge(df1,df2,on = Req,)
但是没有提供我想要的输出,请帮助,谢谢!!
I tried pd.merge(df1, df2, on = "Req", )
but it is not giving my desired output, please help, thanks in advance!
推荐答案
您可以使用 合并
左联接,替换 NaN
s,重命名列,最后添加新列分配
:
You can use merge
with left join, replace NaN
s, rename columns and last add new column with assign
:
df = (pd.merge(df1, df2, on = "Req", how='left')
.fillna(0)
.rename(columns={'Count_x':'from_1','Count_y':'from_2'})
.assign(total=lambda x: x['from_1'] + x['from_2'])
)
print (df)
from_1 Req from_2 total
0 1 Req 1 0.0 1.0
1 2 Req 2 1.0 3.0
2 1 Req 3 0.0 1.0
这篇关于如何基于 pandas 中的列合并两个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文