Bitwise operations in Pandas that return numbers, not bools?

Question

How to perform bitwise operations in Pandas?

How it &works with integers

In integers, the operator &performs a bitmask

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

How it &works in Pandas

Is there a way to perform bitwise masking operations in Pandas? The operator &is doing something else.

>>> 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
+4
source share
1 answer
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

He even returns the series - pretty cool!

+6
source

Source: https://habr.com/ru/post/1530470/


All Articles