Skip to content

NumPy - 数组创建例程

NumPy 提供了多个函数,用于从头创建新的数组(ndarray 对象,NumPy 数组对象)。它们是进行数值计算的基本构建块。

创建一个给定形状和数据类型但不初始化其内容的数组。数组中的值将是当时该内存位置上的任意值。

numpy.empty(shape, dtype=float, order='C')

参数:

参数描述
shape数组的期望形状(整数或整数元组)。
dtype数组元素的期望数据类型(可选,默认为 float64)。
order内存布局:‘C’ 表示行主序(C 风格),‘F’ 表示列主序(Fortran 风格)。可选,默认为 ‘C’。

创建一个 3x2 的整型空数组。请注意初始值是任意的。

import numpy as np
# 创建一个形状为 (3, 2)、类型为整型的空数组
x = np.empty([3, 2], dtype=int)
print(f"Empty array (values are uninitialized):\n{x}")

输出(值可能不同):

Empty array (values are uninitialized):
[[46575369556216 140681880190976]
[ 0 0]
[ 0 0]]

注意: 只有当你计划立即填充数组时才使用 np.empty。依赖未初始化的值是不安全的。

创建一个给定形状和数据类型,并完全用零填充的数组。

numpy.zeros(shape, dtype=float, order='C')

参数与 np.empty 相同。

import numpy as np
# 包含五个零的数组。默认 dtype 为 float64。
x = np.zeros(5)
print(f"Zeros array (float default): {x}")
print(f"dtype: {x.dtype}")

输出:

Zeros array (float default): [0. 0. 0. 0. 0.]
dtype: float64
import numpy as np
# 包含五个零的数组,类型为整型。
x = np.zeros(5, dtype=int) # 在这里使用 Python 内置的 int 类型是没问题的
# 或者指定一个 NumPy 类型:x = np.zeros(5, dtype=np.int32)
print(f"Zeros array (integer): {x}")
print(f"dtype: {x.dtype}")

输出(dtype 可能是 int64 或 int32,具体取决于系统):

Zeros array (integer): [0 0 0 0 0]
dtype: int64

示例 3:使用自定义结构化 dtype 创建零数组

Section titled “示例 3:使用自定义结构化 dtype 创建零数组”

NumPy 允许创建具有结构化数据类型的数组,类似于 C 语言中的结构体(structs)。

import numpy as np
# 定义一个结构化 dtype,包含两个整数字段 'x' 和 'y'
dt = np.dtype([('x', 'i4'), ('y', 'i4')]) # i4 是 32 位整型
# 使用此 dtype 创建一个 2x2 数组,初始化为零
x = np.zeros((2, 2), dtype=dt)
print(f"Zeros array with structured dtype:\n{x}")
print(f"\nAccessing field 'x':\n{x['x']}")

输出:

Zeros array with structured dtype:
[[(0, 0) (0, 0)]
[(0, 0) (0, 0)]]
Accessing field 'x':
[[0 0]
[0 0]]

创建一个给定形状和数据类型,并完全用一填充的数组。

numpy.ones(shape, dtype=None, order='C')

参数与 np.zeros 相同。dtype=None 默认为 float64。

import numpy as np
# 包含五个一的数组。默认 dtype 为 float64。
x = np.ones(5)
print(f"Ones array (float default): {x}")
print(f"dtype: {x.dtype}")

输出:

Ones array (float default): [1. 1. 1. 1. 1.]
dtype: float64
import numpy as np
# 包含一的 2x2 数组,类型为整型
x = np.ones([2, 2], dtype=int)
print(f"Ones array (integer):\n{x}")
print(f"dtype: {x.dtype}")

输出:

Ones array (integer):
[[1 1]
[1 1]]
dtype: int64

NumPy 还提供了 empty_like()、zeros_like() 和 ones_like() 函数。它们创建一个与给定输入数组具有相同形状和数据类型的新数组,但分别用未初始化的值、零或一填充。

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
zeros_arr = np.zeros_like(a)
ones_arr = np.ones_like(a)
print(f"Original array shape: {a.shape}, dtype: {a.dtype}")
print(f"zeros_like array shape: {zeros_arr.shape}, dtype: {zeros_arr.dtype}\n{zeros_arr}")
print(f"ones_like array shape: {ones_arr.shape}, dtype: {ones_arr.dtype}\n{ones_arr}")

输出:

Original array shape: (2, 3), dtype: float32
zeros_like array shape: (2, 3), dtype: float32
[[0. 0. 0.]
[0. 0. 0.]]
ones_like array shape: (2, 3), dtype: float32
[[1. 1. 1.]
[1. 1. 1.]]