Using numpy's binary_repr()
you can convert a given integer to its binary representation as the name indicates. The width
parameter enables for outputs of given length (8 in this case). However, applying this to matrices or arrays will yield the issue of missing leading zeros. This can be tackled by either using strings in the binary representation or the use of zfill()
as demonstrated here.
So giving examples of possible solutions:
import numpy as np
data = np.random.randint(0,100,(2,3), dtype=int)
print(data)
n,m = data.shape
data_bin = np.zeros((n, m), dtype=int)
for i in range(n):
for j in range(m):
data_bin[i, j] = np.binary_repr(data[i, j], width=8)
print(data_bin)
data_bin_str = np.zeros((n, m), dtype='|S8')
for i in range(n):
for j in range(m):
data_bin_str[i, j] = str(np.binary_repr(data[i, j], width=8))
print(data_bin_str)
Note the loop-setup as binary_repr()
has no array support as far as i know (see here).