NumPy astype()

astype() 方法将数组转换为指定的数据类型。

示例

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() 语法

astype() 的语法是

ndarray.astype(dtype, order = 'K', casting = 'unsafe', subok = True, copy = True)

astype() 参数

astype() 方法接受五个参数

  • dtype - 新数组所需的所需数据类型
  • order (可选) - 返回数组的内存布局顺序
  • casting (可选) - 转换数据类型时的转换行为
  • subok (可选) - 确定当数据类型更改时是否对输出数组进行子类化,或者返回基类数组
  • copy (可选) - 如果为 True,则创建副本,如果为 False,则修改原始数组

astype() 返回值

astype() 方法返回修改后的数组

  • 如果 copy 参数为 True,则返回新数组。
  • 如果 copy 参数为 False,则修改原始数组。

示例 1:将整数数组转换为不同的数据类型

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)

输出

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']

在 astype() 中使用可选的 order 参数

order 参数指定数组元素在内存中的存储顺序。

order 可以是:

  • 'C' - 按行展平元素(C 风格顺序)
  • 'F' - 按列展平元素(Fortran 风格顺序)
  • 'A' - 尝试保留原始数组的顺序,否则默认为 C 顺序。
  • 'K' - 按内存中的顺序展平元素,并默认使用 C 顺序。

让我们看一个例子。

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')

输出

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 

在 astype() 中使用可选的 casting 参数

casting 参数指定了在转换数据类型时的转换行为。

casting 可以是:

  • 'no' - 完全不允许数据类型转换
  • 'equiv' - 只允许字节顺序的更改
  • 'safe' - 只允许能保留值的转换
  • 'same_kind' - 只允许安全转换或相同种类内的转换
  • 'unsafe' - 可以进行任何数据转换

让我们看一个例子。

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)

输出

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']

在 astype() 中使用可选的 subok 参数

subok 参数指定是否在返回的数组中使用子类实例(如果可用)。

subok 可以是

  • True- 结果数组保留子类
  • False - 结果数组不保留子类
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))

输出

Original Array Type: <class '__main__.CustomArray'>
Float Array1 Type: <class '__main__.CustomArray'>
Float Array2 Type: <class 'numpy.ndarray'>

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战