创建时指定数据类型
虽然 NumPy 的自动类型推断很有用,但你通常需要显式地定义数组的数据类型,以提高内存效率或满足特定计算的要求。你可以在创建数组时使用 dtype 参数来完成此操作。
不同的数据类型占用不同的内存量:
int32 每个元素占用 4 字节
int64 每个元素占用 8 字节
float32 每个元素占用 4 字节
float64 每个元素占用 8 字节
对于大型数组,选择正确的数据类型可以节省大量内存,并可能提高性能。
让我们创建一个数组并将其数据类型指定为 32 位浮点数。请使用以下代码修改你的 main.py 文件。你可以注释掉或删除上一步的代码。
## Create an array and specify the data type as float32
## The dtype parameter tells NumPy to store each number as a 32-bit float
arr_float = np.array([1.0, 2.5, 3.8], dtype=np.float32)
## Print the data type and the array
print("Data type of arr_float:", arr_float.dtype)
print("Array arr_float:", arr_float)
保存文件并再次运行它。
python main.py
输出将显示数组已使用你指定的数据类型 float32 创建。
Data type of arr_float: float32
Array arr_float: [1. 2.5 3.8]
你可以使用各种数据类型字符串或 NumPy 对象,例如 float32 的 'f4',int64 的 'i8',或布尔值的 np.bool_。