method
Copy of the array, cast to a specified type.
Typecode or data-type to which the array is cast.
Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
New in version 2.4: Support for 'same_value' was added.
If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
When casting using 'same_value' and the values change or would overflow
>>> import numpy as np >>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5])
>>> x.astype(int) array([1, 2, 2])
>>> x.astype(int, casting="same_value") Traceback (most recent call last): ... ValueError: could not cast 'same_value' double to long
>>> x[:2].astype(int, casting="same_value") array([1, 2])
© 2005–2024 NumPy Developers
Licensed under the 3-clause BSD License.
https://numpy.org/doc/2.4/reference/generated/numpy.ma.MaskedArray.astype.html