使用boolean时python的〜发生了什么?

K J*_*nes 19 python boolean pandas

在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

Run Code Online (Sandbox Code Playgroud)

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

我只是在梦到这种用法有效吗?

WeN*_*Ben 15

啊,由于您c是使用DataFrame构造函数创建的T

第一让我们看一下我们以前拥有的东西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
Run Code Online (Sandbox Code Playgroud)

因此,pandas将使每一列只有一个 dtype,否则将转换为object

T每列有什么数据类型之后

dtypes你的c

c.dtypes
Out[608]: 
Classification    object
Boolean           object
Run Code Online (Sandbox Code Playgroud)

Boolean columns成为objecttype,这就是为什么您得到意外输出的原因~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
Run Code Online (Sandbox Code Playgroud)

  • 在我的实际数据集中,该列作为一个对象出现。基于WenYoBen的响应,我应该将我的列设为布尔dtype。`df.column_x = df.column_x_.astype(bool); df [〜df.column_x]` (2认同)