gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:23:50 25 4
gpt4 key购买 nike

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

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/

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