Vectorization conversion of decimal integer arrays to binary arrays in numpy
I’m trying to convert an array of integers to their binary representation in Python. I know native python has a function called bin
that does this. Numpy has a similar function: numpy.binary_repr
.
The problem is that these are not vectorization methods because they only take one value at a time. So in order to convert the entire input array, I have to use a for loop and call these functions multiple times, which is not very efficient.
Is there any way to perform this conversion without using a for loop? Are there any vectorized forms of these features? I tried numpy.apply_along_axis
without success. I’ve also tried using np.fromiter
and map
, but it doesn’t work either.
I know similar questions have been asked several times (e.g. here). ), but none of the answers given are actually vectorized.
Pointing me in any direction would be appreciated!
Thanks =)
Solution
The easiest way is to use binary_repr
and vectorize
, which will preserve the original array shapes, for example:
binary_repr_v = np.vectorize(np.binary_repr)
x = np.arange(-9, 21).reshape(3, 2, 5)
print(x)
print()
print(binary_repr_v(x, 8))
Output:
[[[-9 -8 -7 -6 -5]
[-4 -3 -2 -1 0]]
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
[[11 12 13 14 15]
[16 17 18 19 20]]]
[[['11110111' '11111000' '11111001' '11111010' '11111011']
['11111100' '11111101' '11111110' '11111111' '00000000']]
[['00000001' '00000010' '00000011' '00000100' '00000101']
['00000110' '00000111' '00001000' '00001001' '00001010']]
[['00001011' '00001100' '00001101' '00001110' '00001111']
['00010000' '00010001' '00010010' '00010011' '00010100']]]