Convert numpy scalar to simple python type

I have a numpy array with a single value (scalar) that I would like to convert to match the Python data type. For instance:

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 an easy way to achieve this?

+4
source share
3 answers

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) 

must work

+6
source

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

 import numpy as np a = np.array(3) b = np.array('3') print(type(a.item())) # <class 'int'> print(type(b.item())) # <class 'str'> 
+7
source

This will distinguish ints from str and str to int without requiring you to know the type in advance. What he does is define to call ((str) or (int) on (a / b). Inline 'a if b else c' is equivalent to the ternary operator: (which you may know).

 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)) 

It produces:

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

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

0
source

All Articles