Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operations in Pandas that return numbers rather than bools?

Question

How can I perform bitwise operations in 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

Is there some way to perform bitwise masking operations in Pandas? The & operator does 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
like image 411
MRocklin Avatar asked Mar 06 '14 17:03

MRocklin


1 Answers

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!

like image 154
unutbu Avatar answered Sep 23 '22 17:09

unutbu