亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 pd.merge() 合并兩個以上的數據幀

使用 pd.merge() 合并兩個以上的數據幀

開心每一天1111 2023-08-22 16:06:36
我嘗試根據特定列(“文件名”)使用 pd.merge() 合并 4 個 csv 文件。我讀到合并僅適用于兩個數據幀,而是嘗試按連續步驟合并前兩個數據幀,然后是第三個數據幀,然后是第四個數據幀。這最終成功了,代碼如下:combine = pd.merge(file1, file2, on='filename', how='inner')combine1 = pd.merge(combine, file3, on='filename', how='inner')combine2 = pd.merge(combine1, file4, on='filename', how='inner')產生以下結果:filename,  count_x,  count_y,  count_x,  count_yM116_13331848_13109013422677.jpg,  21,  11,  18,  16M116_13331848_13109013387678.jpg,  21,  13,  13,  18M116_13331848_13109013329679.jpg,  19,  15,  16,  15M116_13331848_13109013424677.jpg,  18,  13,  16,  15M116_13331848_13109013385678.jpg,  17,  12,  15,  13正如您所看到的,該過程在列上生成了令人困惑的標題。因此,我嘗試使用 suffixes 參數來控制這些標頭。但是,這只適用于第一個 pd.merge() 命令,不適用于第二個/第三個命令。這是我的完整腳本:如何將我自己的標題歸因于組合 df 中的每一列?謝謝你,R
查看完整描述

1 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

也許您可以suffixes在合并中使用參數來控制列名稱。來自pandas 合并文檔:


將 DataFrame df1 和 df2 與附加到任何重疊列的指定左后綴和右后綴合并。


在上面,類似:


combine = pd.merge(file1, file2, on='filename', how='inner', suffixes=('_file1', '_file2'))

其他方面也類似merge。這樣你就可以在合并時知道計數來自哪里。


例子:


# Creating Dataframes

df1 = pd.DataFrame({'col1': ['foo', 'bar', 'baz'], 'count': [1, 2, 3]})

df2 = pd.DataFrame({'col1': ['foo', 'bar', 'baz'], 'count': [5, 6, 7]})

df1:


    col1    count

0   foo      1

1   bar      2

2   baz      3

df2:


    col1    count

0   foo      5

1   bar      6

2   baz      7

合并


pd.merge(df1, df2, on='col1', suffixes=('_df1', '_df2'))

結果:


    col1    count_df1   count_df2

0   foo        1         5

1   bar        2         6

2   baz        3         7

更新

鑒于您有四個數據框,也許您可以嘗試:


# Combine two of them

combine1 = pd.merge(file1, file2, on='filename', how='inner', suffixes=('_file1', '_file2'))


# Combine other two

combine2 = pd.merge(file3, file4, on='filename', how='inner', suffixes=('_file3', '_file4'))


# Now combine the combined dataframes

combine = pd.merge(combine1, combine2, on='filename', how='inner')


查看完整回答
反對 回復 2023-08-22
  • 1 回答
  • 0 關注
  • 1653 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號