Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

python - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...