介绍
本教程将探讨 NumPy 数组的属性,重点介绍 dtype 属性。NumPy 是 Python 中用于数值计算的强大库,而 NumPy 数组是该库的核心数据结构。
NumPy 数组是多维、同质的数组,这意味着它们可以在多个维度中存储相同数据类型的元素。它们对于数值操作非常高效且方便,提供了许多功能和能力。
本教程将探讨 NumPy 数组的属性,重点介绍 dtype 属性。NumPy 是 Python 中用于数值计算的强大库,而 NumPy 数组是该库的核心数据结构。
NumPy 数组是多维、同质的数组,这意味着它们可以在多个维度中存储相同数据类型的元素。它们对于数值操作非常高效且方便,提供了许多功能和能力。
在探索 NumPy 数组属性之前,我们先来创建一个 NumPy 数组。你可以使用 numpy.array() 函数从列表、元组或其他数组中创建 NumPy 数组。
在终端中输入以下命令以打开 Python shell。
python3
现在你可以使用 numpy.array() 函数来创建 NumPy 数组。
import numpy as np
## 从列表创建一维数组
one_d_array = np.array([1, 2, 3, 4, 5])
## 从列表的列表创建二维数组
two_d_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
NumPy 数组具有多个属性,这些属性提供了数组的相关信息,例如:
shape:表示数组维度的元组。size:数组中元素的总数。ndim:数组的维度(轴)。dtype:数组元素的数据类型。itemsize:数组中每个元素的大小(以字节为单位)。现在,我们可以在实践中使用这些属性:
## 创建一个二维数组
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
## 获取数组的形状
print("Shape:", array.shape) ## 输出:(3, 3)
## 获取数组的大小
print("Size:", array.size) ## 输出:9
## 获取数组的维度数
print("Number of dimensions:", array.ndim) ## 输出:2
## 获取数组元素的数据类型
print("Data type:", array.dtype) ## 输出:int64 (或 int32,取决于你的系统)
## 获取数组中每个元素的大小(以字节为单位)
print("Item size:", array.itemsize) ## 输出:8 (或 4,取决于你的系统)
dtype 属性尤为重要,因为它决定了数组中存储的数据类型。NumPy 支持多种数据类型,例如整数(int8、int16、int32、int64)、无符号整数(uint8、uint16、uint32、uint64)、浮点数(float16、float32、float64)以及复数(complex64、complex128)。
在创建 NumPy 数组时,你可以使用 dtype 参数指定数据类型。如果未指定,NumPy 会尝试从输入数据中推断数据类型。
让我们来探索如何使用 dtype 属性:
## 从列表创建一个浮点数数组
float_array = np.array([1.2, 2.3, 3.4, 4.5], dtype=np.float32)
print("Float array dtype:", float_array.dtype) ## 输出:float32
## 从列表创建一个整数数组
int_array = np.array([1, 2, 3, 4, 5], dtype=np.int16)
print("Integer array dtype:", int_array.dtype) ## 输出:int16
## 从列表创建一个复数数组
complex_array = np.array([1 + 2j, 2 + 3j, 3 + 4j], dtype=np.complex64)
print("Complex array dtype:", complex_array.dtype) ## 输出:complex64
## 创建一个数组并让 NumPy 推断数据类型
mixed_array = np.array([1, 2, 3.5, 4.5])
print("Mixed array dtype:", mixed_array.dtype) ## 输出:float64
## 更改现有数组的数据类型
new_dtype_array = mixed_array.astype(np.int32)
print("New dtype array:", new_dtype_array) ## 输出:[1 2 3 4]
print("New dtype:", new_dtype_array.dtype) ## 输出:int32
## 创建一个指定数据类型的全零数组
zeros_array = np.zeros((3, 3), dtype=np.uint8)
print("Zeros array with dtype uint8:\n", zeros_array) ## 输出:[[0 0 0] [0 0 0] [0 0 0]]
总结来说,本教程重点介绍了 NumPy 数组的属性,特别是 dtype 属性。我们涵盖了 NumPy 数组的创建,探讨了重要的属性,并深入了解了 dtype 的重要性。理解并有效使用 dtype 属性对于使用 NumPy 数组在 Python 中进行高效且准确的数值计算至关重要。继续练习以提高你对 NumPy 数组及其属性的熟练度。