Pandas 中的按位运算返回数字而不是布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22231438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:47:11  来源:igfitidea点击:

Bitwise operations in Pandas that return numbers rather than bools?

pythonpandasbit-manipulation

提问by MRocklin

Question

How can I perform bitwise operations in Pandas?

如何在 Pandas 中执行按位运算?

How &works on integers

如何&处理整数

On integers the &operator performs a bitwise mask

在整数上,&运算符执行按位掩码

>>> mask = 0b1100  # 4 and 8 bits on
>>> 7 & mask
4

How &works in Pandas

如何&工作在Pandas

Is there some way to perform bitwise masking operations in Pandas? The &operator does something else.

有没有办法在 Pandas 中执行按位掩码操作?该&运营商做别的事情。

>>> df = DataFrame([1, 2, 3, 4, 5, 6, 7, 8], columns=['data'])
>>> df.data & mask
0    False
1    False
2    False
3     True
4     True
5     True
6     True
7     True
Name: data, dtype: bool

回答by unutbu

In [184]: df = pd.DataFrame([1, 2, 3, 4, 5, 6, 7, 8], columns=['data'])

In [185]: mask = 0b1100

In [186]: np.bitwise_and(df['data'], mask)
Out[186]: 
0    0
1    0
2    0
3    4
4    4
5    4
6    4
7    8
Name: data, dtype: int64

It even returns a Series -- pretty cool!

它甚至返回一个系列——非常酷!