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

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

array.dtype

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

示例

import numpy as np
# Create a numpy array
a = np.array([21.23, 13.1, 52.1, 8, 255])
# Print the array
print(a)
# Print the array dat type
print(a.dtype)

输出结果

运行上面的代码给我们以下结果-

[ 21.23 13.1 52.1 8. 255. ]
float64

array.astype

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

示例

import numpy as np
# Create a numpy array
a = np.array([21.23, 13.1, 52.1, 8, 255])
# Print the array
print(a)
# Print the array dat type
print(a.dtype)
# Convert the array data type to int32
a_int = a.astype('int32')
print(a_int)
print(a_int.dtype)
# Convert the array data type to str
a_str = a.astype('str')
print(a_str)
print(a_str.dtype)
# Convert the array data type to complex
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