[英]Merging two Excel files by ID and combining columns with same name (python, pandas)
我是stackoverflow和python熊貓的新手。 我在尋找使用Python 2.7按ID將兩個Excel文件合並為一個Excel文件的文章中找到了答案的一部分
但是,我也想合並或合並兩個具有相同名稱的Excel文件中的列。 我以為下面的帖子會有我的答案,但是我想標題不正確: 合並具有相同列名的Pandas DataFrames
現在我有代碼:
import pandas as pd
file1 = pd.read_excel("file1.xlsx")
file2 = pd.read_excel("file2.xlsx")
file3 = file1.merge(file2, on="ID", how="outer")
file3.to_excel("merged.xlsx")
file1.xlsx
ID,JanSales,FebSales,測試
1100200,汽車
2200500,
3300400,船
file2.xlsx
ID,CreditScore等,EMMAScore,測試
2,良好的,沃森,飛機
3,還好,湯普森,
4,不那么好,NA,
我得到的是merged.xlsx
ID,JanSales,FebSales, test_x ,CreditScore,EMMAScore, test_y
1100200,汽車不同,NaN,NaN的,
2200500,好,沃森,飛機
3300400,船,還好,湯普森,
4,為NaN,NaN的,,不那么好,NaN的,
我想要的是merged.xlsx
ID,JanSales,FebSales,CreditScore,EMMAScore, test
1100200大,NaN,NaN的,汽車
2200500,好,沃森,飛機
3300400,還好,湯普森,船
4,為NaN,NaN的,不那么好,NaN的,萘乙酸
在我的實際數據中,有200多個列與示例中的“測試”列相對應。 我希望程序在file1.xlsx和file2.xlsx中找到具有相同名稱的這些列,並將它們合並在合並的文件中。
好的,這是一種更加動態的方式,在合並之后,我們假設將發生沖突並導致“ column_name_x”或“ _y”。
因此,首先找出通用列名稱,然后從此列表中刪除“ ID”
In [51]:
common_columns = list(set(list(df1.columns)) & set(list(df2.columns)))
common_columns.remove('ID')
common_columns
Out[51]:
['test']
現在,我們可以遍歷此列表以創建新列,並使用where
來根據哪個值不為null來有條件地分配該值。
In [59]:
for col in common_columns:
df3[col] = df3[col+'_x'].where(df3[col+'_x'].notnull(), df3[col+'_y'])
df3
Out[59]:
ID JanSales FebSales test_x CreditScore EMMAScore test_y test
0 1 100 200 cars NaN NaN NaN cars
1 2 200 500 NaN good Watson planes planes
2 3 300 400 boats okay Thompson NaN boats
3 4 NaN NaN NaN not-so-good NaN NaN NaN
[4 rows x 8 columns]
然后只需結束所有多余的列:
In [68]:
clash_names = [elt+suffix for elt in common_columns for suffix in ('_x','_y') ]
clash_names
df3.drop(labels=clash_names, axis=1,inplace=True)
df3
Out[68]:
ID JanSales FebSales CreditScore EMMAScore test
0 1 100 200 NaN NaN cars
1 2 200 500 good Watson planes
2 3 300 400 okay Thompson boats
3 4 NaN NaN not-so-good NaN NaN
[4 rows x 6 columns]
上面的代碼段是這樣的: 給列表元素加上前綴列表前綴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.