HOWTO · NumPy
追加到 NumPy 中的空数组
有两种主要方法可用于在 Python 中将新行附加到空的 NumPy 数组,即 numpy.empty() 函数和 list 方法。
本页内容
本教程将介绍在 Python 中将新行附加到空 NumPy 数组的方法。
使用 numpy.append() 函数附加到 NumPy 空数组
如果我们有一个空数组并想在循环中向其追加新行,我们可以使用 numpy.empty() 函数。由于在 Python 中初始化之前没有为变量分配数据类型,因此我们必须在创建空数组时指定数组元素的数据类型和结构。这可以在 numpy.empty() 函数 内完成。然后我们可以使用 numpy.append() 函数将新行附加到空数组中。请参考以下代码示例。
import numpy as np
array = np.empty((0, 3), int)
array = np.append(array, np.array([[1, 3, 5]]), axis=0)
array = np.append(array, np.array([[2, 4, 6]]), axis=0)
print(array)
输出:
[[1 3 5]
[2 4 6]]
我们首先创建了一个空数组,并使用 np.empty() 函数定义了它的结构和数据类型。然后,我们使用 np.append() 函数沿 array 的 0 轴附加两行。
使用 Python 中的 List 方法附加到 NumPy 空数组
我们也可以通过使用 Python 中的列表数据结构来实现相同的目标。我们可以在 Python 中创建空列表并向它们追加行。list.append() 函数将新元素追加到 Python 中的列表中。然后我们可以使用 numpy.array() 函数将此列表转换为 NumPy 数组。请参考以下代码示例。
import numpy as np
list = []
list.append([1, 3, 5])
list.append([2, 4, 6])
array2 = np.array(list)
print(array2)
输出:
[[1 3 5]
[2 4 6]]
我们首先创建了一个空列表 list 并使用 list.append() 函数将新行附加到 list。最后,我们使用 Python 中的 np.array(list) 函数将 list 转换为 NumPy 数组 array2。