[英]Join dataframe in Python Pandas
您可以使用concat()
和groupby()
。 因為要對 apple_wgt_colour 和 apple_wgt_no_colour 的相應值求和,所以最后應該使用agg()
求和。
您首先應該連接兩個數據框,然后使用 group by 來聚合兩列,apple_wgt_colour 和 apple_wgt_no_colour。
# Generating the two dataframe you exampled.
df1 = pd.DataFrame(
{
'apple_id': [1, 2, 3],
'apple_wgt_1': [9, 16, 8],
'apple_wgt_colour': [9, 6, 8],
'apple_wgt_no_colour': [0, 10, 13],
}
)
df2 = pd.DataFrame(
{
'apple_id': [1, 2, 3],
'apple_wgt_2': [9, 16, 8],
'apple_wgt_colour': [9, 6, 8],
'apple_wgt_no_colour': [0, 10, 13],
}
)
print(df1)
print(df2)
apple_id apple_wgt_1 apple_wgt_colour apple_wgt_no_colour
0 1 9 9 0
1 2 16 6 10
2 3 8 8 13
apple_id apple_wgt_2 apple_wgt_colour apple_wgt_no_colour
0 1 9 9 0
1 2 16 6 10
2 3 8 8 13
下一個代碼將產生您想要的結果:
frames = pd.concat([df1, df2]).groupby('apple_id', as_index=False).agg(sum)
# to change column order as you want
frames = frames[['apple_id', 'apple_wgt_1', 'apple_wgt_2', 'apple_wgt_colour', 'apple_wgt_no_colour']]
print(frames)
apple_id apple_wgt_1 apple_wgt_2 apple_wgt_colour apple_wgt_no_colour
0 1 9.0 9.0 18 0
1 2 16.0 16.0 12 20
2 3 8.0 8.0 16 26
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.