The astype() method converts an array to a specified data type.
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
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.
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.
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
Output
Original Array Type: <class '__main__.CustomArray'> Float Array1 Type: <class '__main__.CustomArray'> Float Array2 Type: <class 'numpy.ndarray'>