python - 按 ID 合并两个 Excel 文件并合并具有相同名称的列(python、pandas)

标签 python excel merge pandas

我是 stackoverflow 和 pandas for python 的新手。我在帖子Looking to merge two Excel files by ID into one Excel file using Python 2.7中找到了我的部分答案

但是,我还想合并或组合两个同名 Excel 文件中的列。我以为下面的帖子会有我的答案,但我想它的标题不正确:Merging Pandas DataFrames with the same column name

现在我有代码:

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")

文件1.xlsx

ID、一月销售、二月销售、测试
1,100,200辆
2,200,500,
3,300,400 艘船

文件2.xlsx

ID、信用评分、EMMAScore、测试
2、好,沃森,飞机
3,好的,汤普森,
4、不太好,不适用,

我得到的是 merged.xlsx

ID、JanSales、FebSales、test_x、CreditScore、EMMAScore、test_y
1,100,200,汽车,NaN,NaN,
2,200,500,,好,沃森,飞机
3,300,400,船,好的,汤普森,
4,NaN,NaN,,不太好,NaN,

我想要的是合并.xlsx

ID、JanSales、FebSales、CreditScore、EMMAScore、测试
1,100,200,NaN,NaN,汽车
2,200,500,好,沃森,飞机
3,300,400,好的,汤普森,船
4,NaN,NaN,不太好,NaN,NaA

在我的真实数据中,有 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]

上面的代码片段来自:Prepend prefix to list elements with list comprehension

关于python - 按 ID 合并两个 Excel 文件并合并具有相同名称的列(python、pandas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24001360/

相关文章:

python - 为什么要在 Fabric 脚本中逐行重新执行 shell 命令?

python - "Select a valid choice."在 Django 中使用 Modelform 时出错

r - 将多个标题表转换为长格式

python - 如何将 pdf 文件中的两页合并为一页

python - 无法使用Python中的请求库登录

python - 使用列表而不是 numpy 数组

python - 将带有数字列的 Pandas 数据框保存为 Excel 中的文本

arrays - 在 VBA 中将一维数组分配给二维数组

pdf - 如何使用 iText API 获取当前页边距

c# - 合并从不同表投影到一个实体的两个可查询对象