考虑数据帧df

df = pd.DataFrame({
    1: [1, 2],
    2: ['a', 3],
    3: [None, 7]
})

df

   1  2    3
0  1  a  NaN
1  2  3  7.0

当我与字符串比较时
df == 'a'



但是,进行移调可以解决问题吗?!
(df.T == 'a').T

       1      2      3
0  False   True  False
1  False  False  False

这是什么错误?我可以通过构建数据框来解决此问题吗?与移调相比有什么不同?

最佳答案

创建数据框时,声明dtype=object:

In [1013]: df = pd.DataFrame({
      ...:     1: [1, 2],
      ...:     2: ['a', 3],
      ...:     3: [None, 7]
      ...: }, dtype=object)

In [1014]: df
Out[1014]:
   1  2     3
0  1  a  None
1  2  3     7

现在,您无需进行换位即可进行比较:
In [1015]: df == 'a'
Out[1015]:
       1      2      3
0  False   True  False
1  False  False  False

我的信念是,一开始,您的列不是对象(在任何可能的地方都被强制),但由于混合值,转置会强制更改。

在源代码 pandas/internals.py 中发现了这一点:
if not isinstance(result, np.ndarray):
    # differentiate between an invalid ndarray-ndarray comparison
    # and an invalid type comparison
    ...
    raise TypeError('Could not compare [%s] with block values' %
                    repr(other))

如果要比较的项目与数组的dtype不匹配,则会引发此错误。

10-05 20:17
查看更多