2

Let's say I have a NumPy array: x = np.array([1, 2, 3, 4, 5]). How do I convert this array into the integer 12345?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Ashinori
  • 57
  • 1
  • 1
  • 6

5 Answers5

4
In [8]: import numpy as np

In [9]: a = np.array([1,2,3,4,5])

In [10]: int("".join(map(str, a)))
Out[10]: 12345
Akavall
  • 82,592
  • 51
  • 207
  • 251
3

Just use the sum() function with a generator:

>>> sum(e * 10 ** i for i, e in enumerate(x[::-1]))
12345

or, alternatively:

>>> sum(e * 10 ** (len(x) - i-1) for i, e in enumerate(x))
12345

or you could use str.join, again with a generator:

>>> int(''.join(str(i) for i in x))
12345

why?

In the first example, we use a generator to yield each number multiplied by 10 to the power of its position in the array, we then add these together to get our final result. This may be easier to see if we use a list-comprehension, rather than a generator to see what is going on:

>>> [e * 10 ** i for i, e in enumerate(x[::-1])]
[5, 40, 300, 2000, 10000]

and then it is clear from here that, through summing these numbers together, we will get the result of 12345. Note, however, that we had to reverse x before using this, as otherwise the numbers would be multiplied by the wrong powers of 10 (i.e. the first number would be multiplied by 1 rather than 10000).

In the second snippet, the code simply uses a different method to get the right power of 10 for each index. Rather than reversing the array, we simply subtract the index from the length of x (len(x)), and minus one more so that the first element is 10000, not 100000. This is simply an alternative.

Finally, the last method should be fairly self-explanatory. We are merely joining together the stringified versions of each number in the array, and then converting back to an int to get our result.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
1

Here's one way via numpy:

import numpy as np

x = np.array([1, 2, 3, 4, 5])
f = np.fromiter((10**(len(x)-i) for i in range(1, len(x)+1)), dtype=int)

y = np.sum(x*f)  # 12345
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Another way is to convert the array into a numpy.string, replace the output spaces with no characters and subset all but the beginning and end then finally convert it to int

import numpy as np

x = np.array([1,2,3,4,5])
y = int(np.str(x).replace(' ','')[1:-1])

Example Run

In [75]: x = np.array([1,2,3,4,5])

In [76]: y = int(np.str(x).replace(' ', '')[1:-1])

In [77]: y
Out[77]: 12345

In [78]: type(y)
Out[78]: int
rayryeng
  • 102,964
  • 22
  • 184
  • 193
0
In [24]: x
Out[24]: array([1, 2, 3, 4, 5])

In [25]: np.dot(x, 10**np.arange(len(x)-1, -1, -1))
Out[25]: 12345
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • 2
    While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value. – SherylHohman Mar 07 '18 at 18:18