我很确定 Pandas 中的 ~ 是 bool 值 not。我发现了几个 StackOverflow 问题/答案,但没有指向官方文档的指针。
完整性检查
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
df = pd.DataFrame([(1, 2, 1),
(1, 2, 2),
(1, 2, 3),
(4, 1, 612),
(4, 1, 612),
(4, 1, 1),
(3, 2, 1),
],
columns=['groupid', 'a', 'b'],
index=['India', 'France', 'England', 'Germany', 'UK', 'USA',
'Indonesia'])
print(df)
filtered = df[~(df['a'] == 2)]
print(filtered)
df是
groupid a b
India 1 2 1
France 1 2 2
England 1 2 3
Germany 4 1 612
UK 4 1 612
USA 4 1 1
Indonesia 3 2 1
和过滤是
groupid a b
Germany 4 1 612
UK 4 1 612
USA 4 1 1
所以我很确定它不是 bool 值。
请您参考如下方法:
~ 是相当于 __invert__ 的运算符为了对 pd.DataFrame/pd.Series 对象执行向量化 逻辑反转,已明确覆盖 dunder。
s = pd.Series([True, False])
~s
0 False
1 True
dtype: bool
s.__invert__()
0 False
1 True
dtype: bool
注意:Dunder 方法不能直接在代码中使用,总是更喜欢使用运算符。
另外,既然你已经问过了,关于 Boolean Indexing 的部分描述了它的用途。
Another common operation is the use of boolean vectors to filter the data. The operators are:
|foror,&forand, and~fornot. These must be grouped by using parentheses.
大胆强调我的。
