Valid options for astype in NumPy

I am new to NumPy and SciPy. Unlike Matlab, it looks like there is a data type associated with each array in NumPy.

Suppose we have an integer array x :

 import numpy as np x = np.array([1, 2, 3]) 

If I want to convert an array to float, then it looks like this:

 y1 = x.astype('float64') # Works! y2 = x.astype('float_') # Works! y3 = x.astype('float') # Works! 

But I'm somewhat puzzled that the following works without single quotes.

 y4 = x.astype(float) # Still works!! 

But for other expressions used for y1 and y2, if I omit the single quote, it does not work:

 y5 = x.astype(float64) # Doesn't work. y6 = x.astype(float_) # Doesn't work. 

So I'm a bit confused about why y4 works, but y5 and y6 cause an error. Can anyone enlighten me on this?

+6
source share
3 answers

Other expressions work, you just need to import the types from numpy. You do not need to do this for float , because it is a built-in type for Python.

 y5 = x.astype(np.float64) y6 = x.astype(np.float_) 

Both inputs of type string and type-type are converted to a numpy.dtype object inside, which you see when using the ndarray.dtype attribute.

+5
source

These 2 do not work because there are no variables with these names in your workspace:

 y5 = x.astype(float64) # Doesn't work. y6 = x.astype(float_) # Doesn't work. 

I get a NameError: name 'float64' is not defined . The error is generated by the Python interpreter before anything is passed to the x.astype method.

You will get the same error if you only entered float64 in the interactive interpreter.

np.float64 works because there is such a variable in the np namespace. This is really a numpy class.

float also works. This is also a class, basic Python (it can also be used as a function, converting a string or number to a float object).

'float64' is a string that astype understands, possibly looking at something in a table. (I could see it).

On the other hand, if I give astype some random string, I get another error

 In [967]: A.astype('bar') ... TypeError: data type "bar" not understood 

np.dtype('bar') gives the same error.

 np.dtype(float) np.dtype('float64') np.dtype('float') 

all return the same dtype('float64') object dtype('float64') .

+2
source

reading astype documentation:

 dtype : str or dtype Typecode or data-type to which the array is cast. 

When you use float without quotes, you use dtype. When you use "float" , you use str.

float64 and float_ are not dtypes in python.

+1
source

All Articles