1

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. based on the questions below i can do what i want. But i prefere to do it all in numpy. I expect it is more efficient because i'm not changing back and forward to numpy arrays. See example:

Example:

import numpy as np


l = np.array([43365644])  # is input array
n = int(43365644)
m = [int(d) for d in str(n)]
o = np.aslist(np.sort(np.asarray(m)))
p = np.asarray(''.join(map(str,o)))

I have tried serval times but without much luck. I had one moment i used the split function and it worked (in the terminal) but after add it to a script it failed again and i was unable to reproduce what i did before..

q = np.sort(np.split(l,1),axis=1) no error but it is still a singel value.

q = np.sort(np.split(l,8),axis=1) With this method it gives the following error:

Traceback (most recent call last):
File "python", line 1, in <module>
ValueError: array split does not result in an equal division

Is there some way that this is possible in numpy? thanks in advance

referenced questions:
Turn a single number into single digits Python
Convert list of ints to one number?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Jan-Bert
  • 921
  • 4
  • 13
  • 22

1 Answers1

2

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)
Nils Werner
  • 34,832
  • 7
  • 76
  • 98