NumPy ndarray.astype()
The numpy.ndarray.astype()
method is used to cast a NumPy array to a specified data type.
It allows for explicit type conversion while providing control over memory order, casting rules, and whether to create a copy of the array.
Syntax
ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
Parameters
Parameter | Type | Description |
---|---|---|
dtype | data-type | The target data type to which the array elements should be converted. |
order | {‘C’, ‘F’, ‘A’, ‘K’}, optional | Defines memory layout order: 'C' (row-major), 'F' (column-major), 'A' (match input), 'K' (match memory layout). |
casting | {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional | Defines casting rules, controlling whether conversions are allowed based on safety. |
subok | bool, optional | If True , subclasses of ndarray are preserved; otherwise, a base ndarray is returned. |
copy | bool, optional | If True , a copy of the array is always created; otherwise, it avoids copying when possible. |
Return Value
Returns a new array with elements cast to the specified dtype
.
If copy=False
and conversion is not required, the original array is returned.
Examples
1. Converting an Integer Array to Float
This example converts an integer array to a float array using astype()
.
import numpy as np
# Creating an integer array
arr = np.array([1, 2, 3, 4, 5])
# Converting to float type
float_arr = arr.astype(float)
# Printing original and converted arrays
print("Original array:", arr)
print("Converted array (float):", float_arr)
Output:
Original array: [1 2 3 4 5]
Converted array (float): [1. 2. 3. 4. 5.]
The integer values are successfully converted to floating-point numbers.
2. Converting a Float Array to Integer
This example demonstrates truncation when converting float values to integers.
import numpy as np
# Creating a float array
arr = np.array([1.9, 2.8, 3.7, 4.5])
# Converting to integer type
int_arr = arr.astype(int)
# Printing original and converted arrays
print("Original array:", arr)
print("Converted array (int):", int_arr)
Output:
Original array: [1.9 2.8 3.7 4.5]
Converted array (int): [1 2 3 4]
Note that floating-point values are truncated, not rounded, during conversion.
3. Converting an Array to Boolean
This example converts numerical values to boolean, where nonzero values become True
and zero becomes False
.
import numpy as np
# Creating an integer array
arr = np.array([0, 1, 2, 0, -3, 4])
# Converting to boolean type
bool_arr = arr.astype(bool)
# Printing original and converted arrays
print("Original array:", arr)
print("Converted array (boolean):", bool_arr)
Output:
Original array: [ 0 1 2 0 -3 4]
Converted array (boolean): [False True True False True True]
Zeros are converted to False
, and all other values are converted to True
.
4. Using casting
Parameter in ndarray.astype()
The casting
parameter controls the safety of type conversions.
import numpy as np
# Creating a float array
arr = np.array([1.2, 2.5, 3.8])
# Safe casting to integer (prevents unsafe conversions)
try:
int_arr = arr.astype(int, casting='safe')
print("Converted array:", int_arr)
except TypeError as e:
print("Error:", e)
Output:
Converted array: [1 2 3]
The safe
casting rule ensures that only safe conversions occur.