首页 > 解决方案 > python的〜在使用布尔值时发生了什么?

问题描述

在 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]

我只是梦想这个用途可以工作吗?

标签: pythonpandasboolean

解决方案


啊,既然你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

所以pandas会让每列只有一个 dtype,如果没有,它将转换为object.

T我们为每列拥有什么数据类型之后

dtypes你的c

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

Boolean columns变成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

推荐阅读