gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:27:20 25 4
gpt4 key购买 nike

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

KeyError:'传递的列并非全部存在数据框'

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

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

这工作正常:


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


但后来我改变了值(value)观,然后:

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' 在英语中没有意义。这意味着“传递的列并不都存在于数据框中”。也就是说,您正在尝试传递数据框中不存在的一列或多列。检查列名中的拼写错误或尾随/前导空格。

关于python - 尝试使用 Python 获取 Excel 差异时如何修复 Key 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com