社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用布尔值时,python的~发生了什么情况?

K Jones • 5 年前 • 1419 次点击  

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]

我是不是在做梦,梦见这是用来工作的?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54531
 
1419 次点击  
文章 [ 1 ]  |  最新文章 5 年前
YOBEN_S
Reply   •   1 楼
YOBEN_S    6 年前

啊,既然你创造了 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 成为 对象 ~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