使用熊猫比较两个具有不同行值和坐标的Excel电子表格

时间:2018-09-05 05:21:42

标签: python excel pandas

我正在做一个比较优秀的程序与熊猫。我制作了一个简单的比较工具,该工具很好用,但它逐行比较并显示列的其他部分中出现的更改。发生这种情况是因为两张纸中的行坐标都不相等。为了澄清一点,这是我的代码:

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

正如我已经说过的那样,问题在于这样的事实,即返回的是逐行的差异,并且差异不正确,因为它们出现在列的不同部分。有谁知道准确比较两个不同行的文件的方法吗?

感谢您的帮助,如果问题有点含糊,则表示抱歉。

1 个答案:

答案 0 :(得分:0)

import pandas as pd
import numpy as np

# Read both Excel files
file1 = pd.read_excel("file1.xlsx", na_values=['NA'])
file2 = pd.read_excel("file2.xlsx", na_values=['NA'])


df2 = file1
df1 = file2


res = df1[df1['samecolname'].isin(df2['samecolname'].unique())]
                   
res2 = df2[df2['samecolname'].isin(df1['samecolname'].unique())]               

res.to_excel('diff1-insecond-but-not-in-first.xlsx',index=False)
res2.to_excel('diff2-in-first-not-in-second.xlsx',index=False)