首页 > 解决方案 > Python 版本 3 - ValueError: no enough values to unpack (expected 2, got 1)

问题描述

尝试执行此 excel 比较脚本时出现上述错误,请帮助。该脚本的目标是能够比较 excel 并突出显示差异,如果您能建议我如何包含主键等列,那就太好了


df1=pd.read_excel('File1.xlsx')
df2=pd.read_excel('File2.xlsx')

df1.equals(df2)

comparison_values = df1.values == df2.values
print (comparison_values)

import numpy as np
rows,cols=np.where(comparison_values==False)

for item in zip(rows,cols):
    df1.iloc[item[0], item[1]] = '{} --> {}'.format(df1.iloc[item[0], item[1]],df2.iloc[item[0], item[1]])

df1.to_excel('./Excel_diff.xlsx',index=False,header=True)


python3 compare_excels.py 
compare_excels.py:8: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
  comparison_values = df1.values == df2.values
False
Traceback (most recent call last):
  File "compare_excels.py", line 12, in <module>
    rows,cols=np.where(comparison_values==False)
ValueError: not enough values to unpack (expected 2, got 1)```

标签: pythonpandas

解决方案


在您的示例中,它似乎df1并且df2都是一维数组。因此,numpy 的where()函数返回一个包含一个值的元组,因此当您键入时:

rows, cols = np.where(comparison_values==False)

您实际上是在尝试将不存在的第二个值分配给cols. 如果要将返回值分配给rows,则应具有以下内容:

rows, = np.where(comparison_values==False) 

推荐阅读