【问题标题】:Comparing two dictionaries of pandas df returns errors when they are identical比较 pandas df 的两个字典在它们相同时返回错误
【发布时间】:2019-09-16 13:12:20
【问题描述】:

我有一本 pandas dfs 字典,我将其转换为如下所示的 pickle 文件:

with open('performance.pkl', 'wb') as handle:
    pickle.dump(performance, handle, protocol=pickle.HIGHEST_PROTOCOL)

然后我像这样加载泡菜文件:

with open('performance.pkl', 'rb') as handle:
    a = pickle.load(handle)

当我检查字典“performance”和“a”的内容时,它们是相同的,但是,如果我这样做:

a == performance

我明白了:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

此外:

a.keys() == performance.keys()
True

a.values == performance.values()
False

(type(a), type(performance) 
(dict, dict)

此外,在逐一比较“a”中的 DF 和“performance”中的 DF 时,它们是相同的。

由于我在比较 python 字典,我不确定问题出在哪里。我不想一个一个循环遍历“a”和“performance”中的DF,因为每个里面有很多索引并且需要时间。

顺便说一句,我不需要保存为泡菜,而是任何其他允许我保存字典的格式。

【问题讨论】:

  • 当你比较字典时,它仍然会比较字典中存储的任何对象。这可以帮助stackoverflow.com/questions/43504568/…
  • 什么是performance,什么是a?它们是字典还是数据框?
  • @QuangHoang。是的。正如问题的标题所说“比较熊猫 DF 的两个字典......”它们是包含熊猫 DF 的字典......出于非常具体的原因这样做。
  • 尝试打印a 看看你得到了什么,因为错误表明你正在比较数据帧。 a 是数据帧字典吗?
  • 在这种情况下,df1 == df2 会产生上述错误。你需要做一个循环:for x in a: a[x].eq(performance[x]).all(None).

标签: python pandas dictionary pickle


【解决方案1】:

试试

a.equals(performance)

参考 - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.equals.html

编辑答案 -

for key1 in a.keys():
    if(a[key1].equals(performance[key1]):
        print(True)
    else:
        print(False)

【讨论】:

  • AttributeError: 'dict' 对象没有属性 'equals'。这不是比较 DF,而是比较包含 DF 的字典。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
相关资源
最近更新 更多