python - 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]
我只是梦想这个用途可以工作吗?
解决方案
啊,既然你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
推荐阅读
- javascript - 如何使用反应测试库测试这个组件 - 只是这个新测试库的初学者
- python - Pandas 数据框搜索的一站式解决方案
- ios - CoreData 扩展:在 NSManagedObjectContext 中插入 NSManagedObject
- javascript - 如何避免在反应功能组件中对“静态组件”进行不必要的重新渲染?
- python-3.x - 如何使用“flask-graphql”将资源管理器添加到 GraphiQL?
- mysql - Tkinter 列表中的 Python 菜单
- html - 在日期选择器中设置语言?
- python - 在 django 中提及或标记用户或任何模型
- postgresql - Liquibase 变更集和 PostgreSQL JSONB 箭头函数
- yaml - Hasura 端点作为环境变量