user3306305
user3306305

Reputation:

Performing bitwise operations on a dataframe

I have a pandas dataframe like this

In [7]:

XYZ

Out[7]:

0     8495872
1     8496128
2     8561408
3     8561664
4     8626944
5     8627200
6     8692736 
7     8692992
8     8693248
9     8693504
10    8758016
11    8758272
12    8758528
13    8758784
14    8759040
15    8823296
16    8823552
17    8823808
18    8824064
19    8824320
20    8824576
21    8824832
22    8888832
23    8890112
Name: XYZ, dtype: int64

I want to convert these values to 32bit binary. I have tried XYZ.apply(bin) function but it gives something like this

0     0b100000011010001100000000
1     0b100000011010010000000000
2     0b100000101010001100000000
3     0b100000101010010000000000
...

there is this unwanted '0b' in front and the output is 24 bit. how to get these values converted to 32 bit without the '0b' part in front?

After the conversion, I am going to do some bitwise and / or operations with those values and generate a new dataframe.

Upvotes: 2

Views: 2507

Answers (1)

parchment
parchment

Reputation: 4002

If you are going to manipulate the bits, you don't need to convert them first. Simply use the bitwise_and and bitwise_or numpy functions on the dataframe's column:

In [14]: import numpy as np

In [15]: df['col']
Out[15]: 
0     5302274
1     4767983
2     6158485
3     9807950
4     4360582
5     2156122
...

In [16]: np.bitwise_and(df['col'], 0b101010)
Out[16]: 
0      2
1     42
2      0
3     10
4      2
5     10

Pandas depends on numpy, so you should already have it installed.

Upvotes: 4

Related Questions