Pandas 中代字号 (~) 的官方文档在哪里?

Where is official documentation for tilde (~) in Pandas?

我很确定 Pandas 中的 ~ 是布尔值 not。我发现了几个 Whosebug 问题/答案,但没有指向官方文档的指针。

完整性检查

#!/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

并且filtered

         groupid  a    b
Germany        4  1  612
UK             4  1  612
USA            4  1    1

所以我很确定它不是布尔值。

我发现它在 this 页面上被引用。它大约在一半的地方,我会用 ctrl+F 导航到它。不过你是对的,它是 not 运算符。

~ 是等价于 __invert__ dunder 的运算符,为了对 pd.DataFrame/pd.Series 个对象。

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: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

大胆强调我的。

如果你去:https://docs.python.org/3/library/operator.html,它说:

Bitwise Inversion   ~ a invert(a)

Here 他们明确定义:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.