在Pandas中返回数字而非布尔值的位运算?
问题
我怎么在Pandas中进行位运算?
&
在整数上的工作原理
在整数上,&
运算符执行的是位掩码操作。
>>> mask = 0b1100 # 4 and 8 bits on
>>> 7 & mask
4
&
在Pandas中的工作原理
在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
1 个回答
11
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
它甚至返回一个序列——真不错!