如何根据 pandas 中的列合并两个数据框
how to merge two dataframes based on a column in 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":["Req 1","Req 2"],"Count":[0,1]})
Req Count
0 Req 1 0
1 Req 2 1
我正在尝试根据 "Req" 列
合并这些 df
我想要的输出是,
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", )
但它没有给出我想要的输出,请帮忙,在此先感谢!
您可以将 merge
与左连接一起使用,替换 NaN
s,重命名列并最后使用 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
我有两个数据框,
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":["Req 1","Req 2"],"Count":[0,1]})
Req Count
0 Req 1 0
1 Req 2 1
我正在尝试根据 "Req" 列
合并这些 df我想要的输出是,
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", )
但它没有给出我想要的输出,请帮忙,在此先感谢!
您可以将 merge
与左连接一起使用,替换 NaN
s,重命名列并最后使用 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