python - pandas.DataFrame.equals 的古怪行为

标签 python pandas

我注意到一个古怪的事情。假设 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

上面我们可以看到,ABa列下的元素是不同的,但是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.

dataframes

使用上述数据帧,当我运行 df.equals() 时,返回的是:

>>> A.equals(B)
Out: True
>>> B.equals(C)
Out: False

这两个与其他答案所说的一致,AB 具有相同的形状和相同的元素,因此它们是相同的。虽然 BC 具有相同的形状,但元素不同,因此它们并不相同。

另一方面:

>>> A.equals(D)
Out: False

此处 AD 具有相同的形状和相同的元素。但他们仍然返回错误。这种情况与上述情况的区别在于,比较中的所有 dtypes 都匹配,正如上面的文档引用所述。 AD 都有 dtypes:str、int、str。

关于python - pandas.DataFrame.equals 的古怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52397773/

相关文章:

python 在没有堆栈跟踪的情况下死于 Windows

python - 将 24 小时值转换为 HHMMSS - 时间

python - 将分组的聚合 nunique 列添加到 pandas 数据框

python - 无法使用 Python 的 mock.patch 模拟 urllib2.urlopen

python - AES-GCM 模式的正确 nonce/iv 大小

python - 如何停止在 Python 中打印 OpenCV 错误消息

python - 使用 str.contains 时有没有办法排除特定子字符串?

python - 如何在 Pandas 中按列表删除行

python - 在同一坐标中绘制/散点位置和标记大小

python - 如何使用正则表达式匹配文本行中任意位置的价格编号?