gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:55:12 32 4
gpt4 key购买 nike

在 pandas DataFrame 中,我有一系列 boolean 值。为了过滤到 boolean 值为 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]

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

最佳答案

啊,既然你使用 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,如果没有它会转换成对象

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

c 中的 dtypes :

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

Boolean columns 变成了 object 类型,这就是为什么你会得到 ~c.Boolean< 的意外输出/p>


如何解决? ---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

关于python - python的〜在使用 boolean 值时发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56079650/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com