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?
In order to change the dtype of the given array object, we will use numpy. astype() function. The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.
NumPy: repeat() function The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.
In NumPy, a scalar is any object that you put in an array. It's similar to the concept in linear algebra, an element of a field which is used to define a vector space. NumPy ensures all scalars in an array have same types. It's impossible one scalar having type int32, the other scalars having type int64.
copy() is supposed to create a shallow copy of its argument, but when applied to a NumPy array it creates a shallow copy in sense B, i.e. the new array gets its own copy of the data buffer, so changes to one array do not affect the other. x_copy = x. copy() is all you need to make a copy of x .
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'>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With