【发布时间】:2019-03-26 07:02:24
【问题描述】:
问题总结
给定 2 个 excel 文件,每个文件大约有 200 列,并且有一个共同的索引列 - 即两个文件中的每一行都有一个 name 属性说,生成一个只有差异的输出 excel 文件最好从excel文件2到excel文件1。 差异将定义为文件 2 中的任何新行而不是 file1 中的任何新行,以及 file2 中具有相同索引(名称)但一个或多个其他列不同的行。 这里有一个很好的例子,它使用了可能有用的熊猫:Compare 2 Excel files and output an Excel file with differences 但是,很难将该解决方案应用于具有 200 列的 excel 文件。
示例文件
以下是 2 个 csv 格式的简化(列从 200 列减少到 4 列)excel 文件的示例,索引列是名称。
Name,value,location,Name Copy
Bob,400,Sydney,Bob
Tim,500,Perth,Tim
Name,value,location,Name Copy
Bob,400,Sydney,Bob
Tim,500,Adelaide,Tim
Melanie,600,Brisbane,Melanie
所以给定以上 2 个输入文件,输出文件应该是:
Name,value,location,Name Copy
Tim,500,Adelaide,Tim
Melanie,600,Brisbane,Melanie
所以输出文件将有 2 行(不包括列标题行),第 2 行是不在 file1 中的新行,第 1 行包含从 file1 到 file2 的更改。
以下工作,但索引列丢失(它是 [1, 2] 而不是 ['Tim', 'Melanie'] :
import pandas as pd
df1 = pd.read_excel('simple1.xlsx', index_col=0)
df2 = pd.read_excel('simple2.xlsx', index_col=0)
df3 = pd.merge(df1, df2, how='right', sort='False', indicator='Indicator')
df4 = df3.loc[df3['Indicator'] == 'right_only']
df5 = df4.drop('Indicator', axis=1)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df5.to_excel(writer, sheet_name='Sheet1')
writer.save()
【问题讨论】:
-
请提供MCVE。就目前而言,很难想象你正在尝试做什么。