Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
NumPy astype()
In this tutorial, you will learn about the Numpy ndarray.astype() method with the help of examples.
The astype() method converts an array to a specified data type.
Example
import numpy as np
# original array of integers
integerArray = np.array([1, 2, 3, 4, 5])
# convert array to floating-point numbers
floatArray = integerArray.astype(float)
print(floatArray)
# Output: [1. 2. 3. 4. 5.]
astype() Syntax
The syntax of astype() is:
ndarray.astype(dtype, order = 'K', casting = 'unsafe', subok = True, copy = True)
astype() Arguments
The astype() method takes five arguments:
dtype- desired data type for the new arrayorder(optional) - memory layout order of the returned arraycasting(optional) - casting behavior when converting data typessubok(optional) - determines whether to subclass the output array if the data type is changed or to return a base-class arraycopy(optional) - creates a copy ifTrue, modifies the original array ifFalse
astype() Return Value
The astype() method returns the modified array:
- If the
copyargument isTrue, a new array is returned. - If the
copyargument isFalse, the original array is modified.
Example 1: Convert an Integer Array to Different Data Types
import numpy as np
# create a 1D array
array = np.array([0, 1, 2, 3, 4, 5])
# convert to different data types
floatArray = array.astype(float)
complexArray = array.astype(complex)
boolArray = array.astype(bool)
stringArray = array.astype(str)
print("Original Array:", array)
print("Float Array:", floatArray)
print("Complex Array:", complexArray)
print("Boolean Array:", boolArray)
print("String Array:", stringArray)
Output
Original Array: [0 1 2 3 4 5] Float Array: [0. 1. 2. 3. 4. 5.] Complex Array: [0.+0.j 1.+0.j 2.+0.j 3.+0.j 4.+0.j 5.+0.j] Boolean Array: [False True True True True True] String Array: ['0' '1' '2' '3' '4' '5']
Using Optional order Argument in astype()
The order argument specifies the order in which the array elements are stored in memory.
The order can be:
'C'- flattens the elements row-wise (in C-style order)'F'- flattens the elements column-wise (in Fortran-style order)'A'- tries to preserve the original array's order, otherwise defaults to C-order.'K'- flattens the elements in the order they occur in memory, and uses C-order by default.
Let's see an example.
import numpy as np
array1 = np.array([[1, 2, 3], [4, 5, 6]])
# list of orders
orders = ['C', 'F', 'A', 'K']
# convert integer array to floating point in different orders
for item in orders:
floatArray = array1.astype(float, order=item)
print(item, 'order Array:\n', floatArray)
print('C_CONTIGUOUS :', floatArray.flags['C_CONTIGUOUS'])
print('F_CONTIGUOUS :', floatArray.flags['F_CONTIGUOUS'],'\n')
Output
C order Array: [[1. 2. 3.] [4. 5. 6.]] C_CONTIGUOUS : True F_CONTIGUOUS : False F order Array: [[1. 2. 3.] [4. 5. 6.]] C_CONTIGUOUS : False F_CONTIGUOUS : True A order Array: [[1. 2. 3.] [4. 5. 6.]] C_CONTIGUOUS : True F_CONTIGUOUS : False K order Array: [[1. 2. 3.] [4. 5. 6.]] C_CONTIGUOUS : True F_CONTIGUOUS : False
Using Optional casting Argument in astype()
The casting argument specifies the casting behavior when converting data types.
The casting can be:
'no'- data types should not be cast at all'equiv'- only byte-order changes are allowed'safe'- only casts which can preserve values are allowed'same_kind'- only safe casts or casts within a kind are allowed'unsafe' - any data conversions may be done
Let's see an example.
import numpy as np
# original array of integers with big-endian byte order
array1 = np.array([1, 2, 3, 4, 5], dtype='>i4')
# casting with 'no' doesn't allow casting to any other data type
array2 = array1.astype(array1.dtype, casting='no')
# casting with 'equiv' allows casting to equivalent data types
array3 = array1.astype('<i4', casting='equiv')
#cCasting with 'safe' allows casting to safe data types preserving precision
array4 = array1.astype(np.float64, casting='safe')
# casting with 'same_kind' allows casting to data types of the same kind
array5 = array1.astype(np.int32, casting='same_kind')
# casting with 'unsafe' allows casting to any data type without checks
array6 = array1.astype(str, casting='unsafe')
print("Array with 'no' casting:", array2)
print("Array with 'equiv' casting:", array3)
print("Array with 'safe' casting:", array4)
print("Array with 'same_kind' casting:", array5)
print("Array with 'unsafe' casting:", array6)
Output
Array with 'no' casting: [1 2 3 4 5] Array with 'equiv' casting: [1 2 3 4 5] Array with 'safe' casting: [1. 2. 3. 4. 5.] Array with 'same_kind' casting: [1 2 3 4 5] Array with 'unsafe' casting: ['1' '2' '3' '4' '5']
Using Optional subok Argument in astype()
The subok argument specifies whether to use subclass instances, if available, for the returned array.
The subok can be:
True- resulting array maintains the subclassFalse- resulting array doesn't maintain the subclass
import numpy as np
# define a custom subclass of ndarray
class CustomArray(np.ndarray):
pass
# create a custom subclass array
array = np.array([1, 2, 3]).view(CustomArray)
# convert the array to float, preserving the subclass
floatArray1 = array.astype(float, subok=True)
# convert the array to float, without preserving the subclass
floatArray2 = array.astype(float, subok=False)
print("Original Array Type:", type(array))
print("Float Array1 Type:", type(floatArray1))
print("Float Array2 Type:", type(floatArray2))
Output
Original Array Type: <class '__main__.CustomArray'> Float Array1 Type: <class '__main__.CustomArray'> Float Array2 Type: <class 'numpy.ndarray'>