我注意到一个古怪的事情。假设 A 和 B 是数据框。
一个是:
A
a b c
0 x 1 a
1 y 2 b
2 z 3 c
3 w 4 d
B 是:
B
a b c
0 1 x a
1 2 y b
2 3 z c
3 4 w d
上面我们可以看到,A
和B
中a
列下的元素是不同的,但是A.equals( B)
产生 True
A==B
正确显示元素不相等:
A==B
a b c
0 False False True
1 False False True
2 False False True
3 False False True
问题:有人可以解释为什么 .equals()
产生 True
吗?另外,我在 SO 上研究了这个主题。根据 contract of pandas.DataFrame.equals , Pandas
必须返回 False
。如果有任何帮助,我将不胜感激。
我是初学者,所以我很感激任何帮助。
这里是A和B的json
格式和._data
一个
`A.to_json()`
Out[114]: '{"a":{"0":"x","1":"y","2":"z","3":"w"},"b":{"0":1,"1":2,"2":3,"3":4},"c":{"0":"a","1":"b","2":"c","3":"d"}}'
A._data
是
BlockManager
Items: Index(['a', 'b', 'c'], dtype='object')
Axis 1: RangeIndex(start=0, stop=4, step=1)
IntBlock: slice(1, 2, 1), 1 x 4, dtype: int64
ObjectBlock: slice(0, 4, 2), 2 x 4, dtype: object
B
B的json格式:
B.to_json()
'{"a":{"0":1,"1":2,"2":3,"3":4},"b":{"0":"x","1":"y","2":"z","3":"w"},"c":{"0":"a","1":"b","2":"c","3":"d"}}'
B._data
BlockManager
Items: Index(['a', 'b', 'c'], dtype='object')
Axis 1: RangeIndex(start=0, stop=4, step=1)
IntBlock: slice(0, 1, 1), 1 x 4, dtype: int64
ObjectBlock: slice(1, 3, 1), 2 x 4, dtype: object
最佳答案
除了 sacul 和 U9-Forward 的回答,我做了一些进一步的分析,看起来你看到 True
而不是你预期的 False
的原因可能与 docs 的这一行有更多关系:
This function requires that the elements have the same dtype as their respective elements in the other Series or DataFrame.
使用上述数据帧,当我运行 df.equals()
时,返回的是:
>>> A.equals(B)
Out: True
>>> B.equals(C)
Out: False
这两个与其他答案所说的一致,A
和 B
具有相同的形状和相同的元素,因此它们是相同的。虽然 B
和 C
具有相同的形状,但元素不同,因此它们并不相同。
另一方面:
>>> A.equals(D)
Out: False
此处 A
和 D
具有相同的形状和相同的元素。但他们仍然返回错误。这种情况与上述情况的区别在于,比较中的所有 dtypes
都匹配,正如上面的文档引用所述。 A
和 D
都有 dtypes
:str、int、str。
关于python - pandas.DataFrame.equals 的古怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52397773/