python - &=、|= 和 ~ 在 Pandas 中做什么

标签 python python-2.7 pandas

我经常在工作中看到这样的代码:

overlap &= group['ADMSN_DT'].loc[i] <= group['epi_end'].loc[j]

我的问题是 &=|=~ 等运算符在 pandas 中的作用是什么?

最佳答案

来自documentation

The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

Augmented assignment statements

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

就像a += 1递增aa &= b比较a b 并将结果分配给 a

a = 1
b = 0
print(a & b)
>>> 0
a &= b
print(a)
>>> 0

还有一个pandas例子

让我们生成一个由 0 和 1 组成的数据框。

import numpy as np
import pandas as pd
a = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD'))
b = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD'))

我们的初始数据框

print(a)
   A  B  C  D
0  0  1  1  0
1  0  0  1  0
2  1  0  0  1
3  1  1  0  0
4  0  0  0  1
5  0  0  0  0
print(b)
   A  B  C  D
0  0  0  0  0
1  1  1  1  0
2  0  1  1  1
3  0  1  1  1
4  1  1  1  0
5  1  1  1  1

第4行ab

print(a.loc[3])
A    1
B    1
C    0
D    0
Name: 1, dtype: int32
print(b.loc[3])
A    0
B    1
C    1
D    1
Name: 1, dtype: int32

现在评估并分配第 4 行

a.loc[3] &= b.loc[3]

a 的第 4 行已更改。只有当两行在相同位置都有 1 时,才会将 1 写回 a

print(a.loc[3])
A    0
B    1
C    0
D    0
Name: 3, dtype: int32

关于python - &=、|= 和 ~ 在 Pandas 中做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40140933/

相关文章:

具有多个列表和 if else 条件的 Python 列表理解

Python Quandl - ModuleNotFoundError

python - 我可以创建一个可以解包的类吗?

python 没有名为 ujson 的模块,虽然它已经安装

Python 类 : How to add a custom method to an existing object (pandas dataframe)

python - Pandas 中的数据透视表出现意外输出

python - 使用 Python Ctypes 的访问冲突

python csv 到字典

python-2.7 - Mincemeat:提供额外的参数来映射和减少带有闭包的函数

python - 按索引索引 Pandas 数据框