数据类型是指定数组将存储的数据类型的一种方式。例如,
array1 = np.array([2, 4, 6])
这里,array1 数组包含三个整数元素,所以数据类型是整数(int64)),这是默认设置。
NumPy 为我们提供了几种内置的数据类型,可以有效地表示数值数据。
NumPy 数据类型
NumPy 提供了比 Python 更广泛的数值数据类型。以下是 NumPy 中最常用的数值数据类型列表:
int8、int16、int32、int64- 不同位数的有符号整数类型uint8、uint16、uint32、uint64- 不同位数的无符号整数类型float32、float64- 不同精度的浮点类型complex64、complex128- 不同精度的复数类型
检查 NumPy 数组的数据类型
要检查 NumPy 数组的数据类型,我们可以使用 dtype 属性。例如,
import numpy as np
# create an array of integers
array1 = np.array([2, 4, 6])
# check the data type of array1
print(array1.dtype)
# Output: int64
在上面的例子中,我们使用 dtype 属性来检查 array1 数组的数据类型。
由于 array1 是一个整数数组,因此 array1 的数据类型默认推断为 int64。
示例:检查 NumPy 数组的数据类型
import numpy as np
# create an array of integers
int_array = np.array([-3, -1, 0, 1])
# create an array of floating-point numbers
float_array = np.array([0.1, 0.2, 0.3])
# create an array of complex numbers
complex_array = np.array([1+2j, 2+3j, 3+4j])
# check the data type of int_array
print(int_array.dtype) # prints int64
# check the data type of float_array
print(float_array.dtype) # prints float64
# check the data type of complex_array
print(complex_array.dtype) # prints complex128
输出
int64 float64 complex128
在这里,我们创建了不同类型的数组,并使用 dtype 属性检查了这些数组的默认数据类型。
int_array- 包含四个整数元素,其默认数据类型为int64float_array- 包含三个浮点数,其默认数据类型为float64complex_array- 包含三个复数,其默认数据类型为complex128
创建具有定义数据类型的 NumPy 数组
在 NumPy 中,我们可以在调用 np.array() 函数时通过传递 dtype 参数来创建具有定义数据类型的数组。例如,
import numpy as np
# create an array of 32-bit integers
array1 = np.array([1, 3, 7], dtype='int32')
print(array1, array1.dtype)
输出
[1 3 7] int32
在上面的例子中,我们创建了一个名为 array1 的 NumPy 数组,并定义了其数据类型。
请注意以下代码,
np.array([1, 3, 7], dtype='int32')
这里,在 np.array() 中,我们传递了一个数组 [1, 3, 7] 并将 dtype 参数设置为 int32。
由于我们将数组的数据类型设置为 int32,因此数组的每个元素都表示为一个 32 位整数。
示例:创建具有定义数据类型的 NumPy 数组
import numpy as np
# create an array of 8-bit integers
array1 = np.array([1, 3, 7], dtype='int8')
# create an array of unsigned 16-bit integers
array2 = np.array([2, 4, 6], dtype='uint16')
# create an array of 32-bit floating-point numbers
array3 = np.array([1.2, 2.3, 3.4], dtype='float32')
# create an array of 64-bit complex numbers
array4 = np.array([1+2j, 2+3j, 3+4j], dtype='complex64')
# print the arrays and their data types
print(array1, array1.dtype)
print(array2, array2.dtype)
print(array3, array3.dtype)
print(array4, array4.dtype)
输出
[1 3 7] int8 [2 4 6] uint16 [1.2 2.3 3.4] float32 [1.+2.j 2.+3.j 3.+4.j] complex64
NumPy 类型转换
在 NumPy 中,我们可以使用 astype() 方法转换数组的数据类型。例如,
import numpy as np
# create an array of integers
int_array = np.array([1, 3, 5, 7])
# convert data type of int_array to float
float_array = int_array.astype('float')
# print the arrays and their data types
print(int_array, int_array.dtype)
print(float_array, float_array.dtype)
输出
[1 3 5 7] int64 [1. 3. 5. 7.] float64
在这里,int_array.astype('float') 使用 astype() 将 int_array 的数据类型从 int64 转换为 float64。
