【问题标题】:What happened to python's ~ when working with boolean?python的〜在使用布尔值时发生了什么?
【发布时间】:2019-09-28 11:37:03
【问题描述】:

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

我只是在梦想这个用途有用吗?

【问题讨论】:

  • stackoverflow.com/questions/21415661/… 评分最低的评论的最后一部分也突出了这个问题
  • 我认为由于布尔值非常小,如果 Python 尝试一起处理布尔值,它们往往会相互纠缠。

标签: python pandas boolean


【解决方案1】:

啊,既然你使用DataFrame构造函数创建了c,那么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

【讨论】:

  • 在我的真实数据集中,列作为对象出现。根据 WenYoBen 的回复,我应该将我的列设为 boolean dtype。 df.column_x = df.column_x_.astype(bool); df[~df.column_x]
猜你喜欢
  • 1970-01-01
  • 2013-11-12
  • 2012-06-26
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多