5

I have a numpy array with a single value (scalar) which I would like to convert to correspoding Python data type. For example:

import numpy as np
a = np.array(3)
b = np.array('3')

I could convert them to int and str by casting:

a_int = int(a)
b_str = str(b)

but I need to know the types in advance. I would like to convert a to an integer and b to a string without explicit type checking. Is there a simple way to achieve it?

btel
  • 4,988
  • 5
  • 33
  • 44

3 Answers3

7

In this case

import numpy as np
a = np.array(3)
b = np.array('3')
a_int = a.tolist()
b_str = b.tolist()
print type(a_int), type(b_str)

should work

YXD
  • 28,479
  • 14
  • 66
  • 108
7

As described here, use the obj.item() method to get the Python scalar type:

import numpy as np
a = np.array(3).item()
b = np.array('3').item()
print(type(a))  # <class 'int'>
print(type(b))  # <class 'str'>
Mike T
  • 34,456
  • 15
  • 128
  • 169
0

This will cast ints to str, and str to int without needing to know the type in advance. What it does is determine to call either (str) or (int) on (a/b). the inline 'a if b else c' is equivalent to the ?: ternary operator (which you may be familiar with).

a = '1'
a_res = (str if type(a) == type(1) else int)(a)
print(type(a_res))

b = 1
b_res = (str if type(b) == type(1) else int)(b)
print(type(b_res))

Produces:

>>> 
<class 'int'>
<class 'str'>

As you can see, the same code is used to convert both a and b.

HennyH
  • 7,296
  • 2
  • 25
  • 38
  • Thanks. This becomes a bit cumbersome when you have more possible types like float, boolean, etc. That's why I prefer answer of Mr E – btel Apr 24 '13 at 13:11