簡體   English   中英

在 Python Pandas 中加入數據框

[英]Join dataframe in Python Pandas

我有兩個數據框如下

數據幀 1

在此處輸入圖片說明

數據幀 2

在此處輸入圖片說明

我想將這兩個數據框合並為如下所示的內容;

在此處輸入圖片說明

我嘗試使用 pd.merge 並加入如下

frames = pd.merge(df1, df2, how='outer', on=['apple_id','apple_wgt_colour', 'apple_wgt_no_colour'])

但結果是這樣的

在此處輸入圖片說明

任何人都可以幫忙嗎?

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM