我正在使用pandas制作一个比较Excel表格的程序。我已经做了一个简单的比较工具,效果不错,但它是逐行比较,并显示出在列的其他部分中出现的更改。这是因为两个表格的行坐标不相等。为了稍微澄清一下,这里是我的代码:
import pandas as pd
import numpy as np
import openpyxl
wb = openpyxl.load_workbook('CK_CBF_Draft_01.2018_original.xlsx')
ws = wb['CBF']
list1 = []
for i in ws['H1':'H365']:
for cell in i:
list1.append(i)
# Define the diff function to show the changes in each field
def report_diff(x):
return x[1] if x[1] in list1 else '{} ---> {}'.format(x[0],x[1])
# We want to be able to easily tell which rows have changes
def has_change(row):
if "--->" in row.to_string():
return "Y"
else:
return "N"
# Read in both excel files
df1 = pd.read_excel('Invoice1.xlsx', 'Sheet1', na_values=['NA'])
df2 = pd.read_excel('Invoice2.xlsx', 'Sheet1', na_values=['NA'])
# Make sure we order by account number so the comparisons work
df1.sort_values(by="Host Name")
df1=df1.reindex()
df2.sort_values(by="Host Name")
df2=df2.reindex()
# Create a panel of the two dataframes
diff_panel = pd.Panel(dict(df1=df1,df2=df2))
#Apply the diff function
diff_output = diff_panel.apply(report_diff, axis=0)
# Flag all the changes
diff_output['has_change'] = diff_output.apply(has_change, axis=1)
#Save the changes to excel but only include the columns we care about
diff_output[(diff_output.has_change == 'Y')].to_excel('my-diff-1.xlsx',index=False,columns=["Host Name","CPU#","Memory","Invoice Total","Quantity"])
print('Worked')
我已经说明的问题是,这会返回逐行差异,而这些差异在列的不同位置上出现时是不正确的。有人知道一种准确比较两个不同行的文件的方法吗?
感谢您的帮助,如果问题有点模糊,请见谅。