繁体   English   中英

尝试使用 Python 获取 Excel 差异时如何修复 Key 错误

[英]How to fix a Key error when trying to get an Excel diff with Python

我正在尝试比较两个 excel 文档并在新文档中获得差异。 我找到了一个教程,阅读并尝试了其中的确切代码,以及来自作者 GitHub 的示例文档(点击: https ://pbpython.com/excel-diff-pandas-update.html)。 它有效,但是当我尝试将电子表格中的值更改为随机值时(我将需要更少的列,因此我一直在摆弄原始文件),我不断收到错误消息:

KeyError: 'passes 列不是全部存在的数据帧'

我保留所有标题,无论我将某些单元格留空还是用文本填充它们,我都会收到错误消息。 我究竟做错了什么?

我没有找到完全相同的错误,这就是我发布这个问题的原因。

这工作正常:


import pandas as pd


# Define the diff function to show the changes in each field
def report_diff(x):
    return x[0] if x[0] == x[1] else '{} ---> {}'.format(*x)

# Read in the two files but call the data old and new and create columns to track
old = pd.read_excel('C:\\Users\\Olga\\Documents\\sample-address-1.xlsx', 'Sheet1', na_values=['NA'])
new = pd.read_excel('C:\\Users\\Olga\\Documents\\sample-address-2.xlsx', 'Sheet1', na_values=['NA'])
old['version'] = "old"
new['version'] = "new"

old_accts_all = set(old['account number'])
new_accts_all = set(new['account number'])

dropped_accts = old_accts_all - new_accts_all
added_accts = new_accts_all - old_accts_all

all_data = pd.concat([old,new],ignore_index=True)
changes = all_data.drop_duplicates(subset=["account number",
                                           "name", "street",
                                           "city","state",
                                           "postal code"], keep='last')

dupe_accts = changes[changes['account number'].duplicated() == True]['account number'].tolist()
dupes = changes[changes["account number"].isin(dupe_accts)]

# Pull out the old and new data into separate dataframes
change_new = dupes[(dupes["version"] == "new")]
change_old = dupes[(dupes["version"] == "old")]

# Drop the temp columns - we don't need them now
change_new = change_new.drop(['version'], axis=1)
change_old = change_old.drop(['version'], axis=1)

# Index on the account numbers
change_new.set_index('account number', inplace=True)
change_old.set_index('account number', inplace=True)

# Combine all the changes together
df_all_changes = pd.concat([change_old, change_new],
                            axis='columns',
                            keys=['old', 'new'],
                            join='outer')

# Define the diff function to show the changes in each field
def report_diff(x):
    return x[0] if x[0] == x[1] else '{} ---> {}'.format(*x)

df_all_changes = df_all_changes.swaplevel(axis='columns')[change_new.columns[0:]]

df_changed = df_all_changes.groupby(level=0, axis=1).apply(lambda frame: frame.apply(report_diff, axis=1))
df_changed = df_changed.reset_index()

df_removed = changes[changes["account number"].isin(dropped_accts)]
df_added = changes[changes["account number"].isin(added_accts)]

output_columns = ["account number", "name", "street", "city", "state", "postal code"]
writer = pd.ExcelWriter("my-diff.xlsx")
df_changed.to_excel(writer,"changed", index=False, columns=output_columns)
df_removed.to_excel(writer,"removed",index=False, columns=output_columns)
df_added.to_excel(writer,"added",index=False, columns=output_columns)
writer.save()

但是后来我更改了值并:


Traceback (most recent call last):
  File "C:\Users\Olga\Documents\exceldiff.py", line 61, in <module>
    df_changed.to_excel(writer,"changed", index=False, columns=output_columns)
  File "C:\Python37\lib\site-packages\pandas\core\generic.py", line 2248, in to_excel
    inf_rep=inf_rep,
  File "C:\Python37\lib\site-packages\pandas\io\formats\excel.py", line 392, in __init__
    raise KeyError("passes columns are not ALL present dataframe")
KeyError: 'passes columns are not ALL present dataframe'

很抱歉让这个问题复活,但我刚刚收到这个错误,并没有找到关于它的文档。 这个错误应该有不同的措辞。 'passes columns are not ALL present dataframe' 在英语中没有意义。 它的意思是“传递的列并不全部出现在数据框中”。 也就是说,您正在尝试传递数据框中不存在的一列或多列。 检查列名称中的拼写错误或尾随/前导空格。

formatted列表为空时,我得到了这个错误passes columns are not all present dataframe ,所以当它为空时我创建了一行。

def generate_excel(file_name: str, formatted: list):
    if not formatted:
        formatted = [{
            'Código/Sigla': '',
            'Placa': '',
            'Tipo vehículo': '',
            'Agencia': '',
            'Hora último evento': ''
        }]

    df = pd.DataFrame.from_dict(formatted)
    
    writer = pd.ExcelWriter('/tmp/%s' % (file_name), engine='xlsxwriter')
    
    sheet_name = 'Hoja 1'
    
    columns = ['Código/Sigla', 'Placa', 'Tipo vehículo', 'Agencia', 'Hora último evento']

    df.to_excel(writer, sheet_name=sheet_name, index=False, columns=columns)  # send df to writer

    worksheet = writer.sheets[sheet_name]  # pull worksheet object

    for idx, col in enumerate(columns):  # loop through all columns
        series = df[col]

        max_len = max((
            series.astype(str).map(len).max(),  # len of largest item
            len(str(series.name))  # len of column name/header
            )) + 1  # adding a little extra space

        worksheet.set_column(idx, idx, max_len)  # set column width
            
    writer.save()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM