在 NumPy 中添加列
Muhammad Maisam Abbas
2021年4月29日

本教程将介绍在 Python 中向 NumPy 数组添加列的方法。
使用 numpy.append()
函数将列添加到 NumPy 数组
numpy.append()
函数可用于向现有的 numpy 数组添加额外的列。numpy.append()
函数具有三个参数,一个是预先存在的数组,要添加的新值,另一个是要向其中添加新值的 axis
。如果要将新列添加到预先存在的数组中,可以将 axis
参数指定为 1
。numpy.append()
函数返回一个新数组,在该数组中,新值将附加到预先存在的数组的末尾。请参见以下代码示例。
import numpy as np
array = np.array([[1, 2], [3, 4], [5, 6]])
array2 = np.append(array, [[1], [1], [1]], axis=1)
array2
输出:
[[1 2 1]
[3 4 1]
[5 6 1]]
在上面的代码中,我们首先使用 Python 中的 numpy.array()
函数初始化了第一个数组 array
。然后,我们使用 Python 中的 numpy.append()
函数初始化了一个新的数组 array2
,包含一个额外的列。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn