Skip to content Skip to sidebar Skip to footer

Split Integer Into Digits Using Numpy

I have a question. The question is asked before but as far as i can see never using numpy. I want split a value in the different digits. do somthing and return back into a number.

Solution 1:

Pretty simple:

  1. Divide your number by 1, 10, 100, 1000, ... rounding down
  2. Modulo the result by 10

which yields

l // 10 ** np.arange(10)[:, None] % 10

Or if you want a solution that works for

  • any base
  • any number of digits and
  • any number of dimensions

you can do

l = np.random.randint(0, 1000000, size=(3, 3, 3, 3))
l.shape
# (3, 3, 3, 3)

b = 10                                                   # Base, in our case 10, for 1, 10, 100, 1000, ...
n = np.ceil(np.max(np.log(l) / np.log(b))).astype(int)   # Number of digits
d = np.arange(n)                                         # Divisor base b, b ** 2, b ** 3, ...
d.shape = d.shape + (1,) * (l.ndim)                      # Add dimensions to divisor for broadcasting
out = l // b ** d % b

out.shape
# (6, 3, 3, 3, 3)

Post a Comment for "Split Integer Into Digits Using Numpy"