更改给定 numpy 数组的数据类型

pythonserver side programmingprogramming更新于 2025/10/19 1:16:17

除了 python 的原生数据类型外,Numpy 数组还支持多种数据类型。创建数组后,我们仍然可以根据需要修改数组中元素的数据类型。用于此目的的两种方法是 array.dtype 和 array.astype

array.dtype

此方法为我们提供数组中元素的现有数据类型。在下面的例子中,我们声明了一个数组并找到它的数据类型。

示例

import numpy as np
# 创建一个 numpy 数组
a = np.array([21.23, 13.1, 52.1, 8, 255])
# 打印数组
print(a)
# 打印数组数据类型
print(a.dtype)

输出

运行上述代码得到以下结果 −

[ 21.23 13.1 52.1 8. 255. ]
float64

array.astype

此方法将现有数组转换为具有所需数据类型的新数组。在下面的例子中,我们获取给定的数组并将其转换为转换为各种目标数据类型。

示例

import numpy as np
# 创建 numpy 数组
a = np.array([21.23, 13.1, 52.1, 8, 255])
# 打印数组
print(a)
# 打印数组数据类型
print(a.dtype)
# 将数组数据类型转换为 int32
a_int = a.astype('int32')
print(a_int)
print(a_int.dtype)
# 将数组数据类型转换为 str
a_str = a.astype('str')
print(a_str)
print(a_str.dtype)
# 将数组数据类型转换为复杂
a_cmplx = a.astype('complex64')
print(a_cmplx)
print(a_cmplx.dtype)

输出

运行上述代码得到以下结果 −

[ 21.23 13.1 52.1 8. 255. ]
float64
[ 21 13 52 8 255]
int32
['21.23' '13.1' '52.1' '8.0' '255.0']
<U32
[ 21.23+0.j 13.1 +0.j 52.1 +0.j 8. +0.j 255. +0.j]
complex64

相关文章


有用资源