.xlsx文件与熊猫合并时出现问题

时间:2018-09-27 17:08:34

标签: python pandas xlsx

我正在使用python 2.7进行操作,我编写了一个脚本,该脚本应使用两个.xlsx文件的名称,并使用pandas将其转换为两个数据帧,然后将它们连接起来。 所考虑的两个文件具有相同的行和不同的列。 基本上,我有以下两个Excel文件:

enter image description here enter image description here

我想保留相同的行,而只合并列。 代码如下:

import pandas as pd

file1 = 'file1.xlsx'
file2 = 'file2.xlsx'
sheet10 = pd.read_excel(file1, sheet_name = 0)
sheet20 = pd.read_excel(file2, sheet_name = 0)

conc1 = pd.concat([sheet10, sheet20], sort = False)
output = pd.ExcelWriter('output.xlsx')
conc1.to_excel(output, 'Sheet 1')
output.save()

而不是按照我的期望(鉴于我在网上阅读了示例),输出变成了这样:

enter image description here

有人知道我可以改善自己的剧本吗? 非常感谢。

2 个答案:

答案 0 :(得分:0)

要使用pd.concat获得预期的输出,两个数据框中的列名应相同。这是怎么做,

# Create a 1:1 mapping of sheet10 and sheet20 columns
cols_mapping = dict(zip(sheet20.columns, sheet10.columns))

# Rename the columns in sheet20 to match with that of sheet10
sheet20_renamed = sheet20.rename(cols_mapping, axis=1)

concatenated = pd.concat([sheet10, sheet20_renamed])

答案 1 :(得分:0)

最好的答案实际上取决于数据的确切形状。根据您提供的示例,看起来在两个数据框之间要对数据进行相同的索引,但要保留的列标题不同。如果是这种情况,这将是最佳解决方案:

import pandas as pd

file1 = 'file1.xlsx'
file2 = 'file2.xlsx'
sheet10 = pd.read_excel(file1, sheet_name = 0)
sheet20 = pd.read_excel(file2, sheet_name = 0)

conc1 = sheet10.merge(sheet20, how="left", left_index=True, right_index=True)
output = pd.ExcelWriter('output.xlsx')
conc1.to_excel(output, sheet_name='Sheet 1', ignore_index=True)
output.save()

由于两个初始数据帧中的行数直接匹配,因此使用左,右,外部或内部联接并不重要。在此示例中,我使用了左联接。

但是,如果两个数据框中的行不能完全对齐,则所选的join方法可能会对您的输出产生巨大影响。我建议您先阅读merge/join/concatenate上的熊猫文档,然后再继续。

相关问题