I have a numpy array consisting of bitstrings and I intend to convert bitstrings to integer base 2 in order to perform some xor bitwise operations. I can convert string to integer with base 2 in python with this:
int('000011000',2)
I am wondering if there is a faster and better way to do this in numpy. An example of numpy array that I am working on is something like this:
array([['0001'],
['0010']],
dtype='|S4')
and I expect to convert it to:
array([[1],[2]])
One could use
np.fromstring
to separate out each of the string bits intouint8
type numerals and then use some maths with matrix-multiplication to convert/reduce to decimal format. Thus, withA
as the input array, one approach would be like so -Sample run -
An alternative method could be suggested to avoid
np.fromstring
. With this method, we would convert to int datatype at the start, then separate out each digit, which should be equivalent ofstr2num
in the previous method. Rest of the code would stay the same. Thus, an alternative implementation would be -Runtime tests
Let's time all the approaches listed thus far to solve the problem, including
@Kasramvd's loopy solution
.Due to KISS principle, I'd like to suggest the following approach using a list comprehension: