Python的布尔类型中使用~发生了什么?

19
在pandas DataFrame中,我有一系列布尔值。为了筛选出布尔值为True的行,我可以使用:df[df.column_x]
我认为为了筛选出只有列为False的行,我可以使用:df[~df.column_x]。我觉得我以前做过这件事,并且已经看到它被接受作为答案。
然而,这会失败,因为~df.column_x将值转换为整数。请参见下面的示例。
import pandas as pd . # version 0.24.2

a = pd.Series(['a', 'a', 'a', 'a', 'b', 'a', 'b', 'b', 'b', 'b'])
b = pd.Series([True, True, True, True, True, False, False, False, False, False], dtype=bool)

c = pd.DataFrame(data=[a, b]).T
c.columns = ['Classification', 'Boolean']```

print(~c.Boolean)

0    -2
1    -2
2    -2
3    -2
4    -2
5    -1
6    -1
7    -1
8    -1
9    -1
Name: Boolean, dtype: object

print(~b)

0    False
1    False
2    False
3    False
4    False
5     True
6     True
7     True
8     True
9     True
dtype: bool

基本上,我可以使用c[~b],但不能使用c[~c.Boolean]

这个用法以前是可以的吗?难道我在做梦吗?


https://dev59.com/CmEi5IYBdhLWcg3wRayf 这篇最差评评论的最后一部分也强调了这个问题 - Chris
我认为布尔值非常小,如果Python尝试一起处理布尔值,它们很容易纠缠在一起。 - einpoklum
1个回答

16
啊,既然您是使用DataFrame构造函数创建了c,那么首先让我们看一下T之前的内容:
pd.DataFrame([a, b])
Out[610]: 
      0     1     2     3     4      5      6      7      8      9
0     a     a     a     a     b      a      b      b      b      b
1  True  True  True  True  True  False  False  False  False  False

因此,pandas将使每列只具有一个dtype,如果不是,则会转换为object

在使用T之后,我们每列拥有什么数据类型

您的c中的dtypes

c.dtypes
Out[608]: 
Classification    object
Boolean           object

Boolean列变成了object类型,这就是为什么您会得到意外输出~c.Boolean的原因。


如何修复?---使用concat函数。

c=pd.concat([a,b],1)
c.columns = ['Classification', 'Boolean']
~c.Boolean
Out[616]: 
0    False
1    False
2    False
3    False
4    False
5     True
6     True
7     True
8     True
9     True
Name: Boolean, dtype: bool

3
在我的真实数据集中,该列以对象的形式出现。根据WenYoBen的回答,我应该将列转换为布尔类型。df.column_x = df.column_x_.astype(bool); df[~df.column_x] - K Jones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接