1

I am searching for a dynamic way to perform a numpy convert (integer to binary).
I tried to use the 'astype' way but it didn't work out.

I got a 3-dim matrix like that one:

x = np.array([[[1, 2, 44],[1,5,3]],[[7, 88, 12],[1,15,60]]])

I would like to convert each value of x to its binary form (max size of 8 bits) for example, if x includes 6 it will be converted to '00000110'.

This is a reference for how to convert integer to binary as I need:
Converting integer to binary in python

Azametzin
  • 5,223
  • 12
  • 28
  • 46
  • What you need is not a type conversion (and that is why `astype` didn't work), but a string representation of the numbers in your array (decimal form into binary form) – alan.elkin Mar 27 '20 at 15:27
  • `bin` (or any equivalent) has to applied to each array element. There isn't compiled method that does that for the whole array at once. – hpaulj Mar 27 '20 at 15:32

1 Answers1

2

Is this what you are looking for?

vfunc = np.vectorize(lambda i: '{0:08b}'.format(i))
x_bin = vfunc(x)

Output of print(x_bin):

[[['00000001' '00000010' '00101100']
  ['00000001' '00000101' '00000011']]

 [['00000111' '01011000' '00001100']
  ['00000001' '00001111' '00111100']]]
alan.elkin
  • 954
  • 1
  • 10
  • 19