append()
方法将值添加到 NumPy 数组的末尾。
示例
import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# append array2 to array1
array3 = np.append(array1, array2)
print(array3)
# Output : [1 2 3 4 5 6]
append() 语法
append()
的语法是
numpy.append(array, values, axis)
append() 参数
append()
方法接受三个参数
array
- 原始数组values
- 要附加到原始数组末尾的数组axis
- 附加值的轴
注意: 如果 axis
为 None
,则数组将被展平并附加。
append() 返回值
append()
方法返回一个附加了值的数组副本。
示例 1:附加数组
import numpy as np
array1 = np.array([0, 1, 2, 3])
array2 = np.array([4, 5, 6, 7])
# append values to an array
array3 = np.append(array1, array2)
print(array3)
输出
[0 1 2 3 4 5 6 7]
示例 2:沿不同轴附加数组
我们可以将 axis
作为 append()
方法的第三个参数传递。axis
参数决定了需要附加新数组的维度(对于多维数组)。
import numpy as np
array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])
# append array2 to array1 along axis 0
array3 = np.append(array1, array2, 0)
# append array2 to array1 along axis 1
# specifying axis argument explicitly
array4 = np.append(array1, array2, axis = 1)
# append array2 to array1 after flattening
array5 = np.append(array1, array2, None)
print('\nAlong axis 0 : \n', array3)
print('\nAlong axis 1 : \n', array4)
print('\nAfter flattening : \n', array5)
输出
Along axis 0 : [[0 1] [2 3] [4 5] [6 7]] Along axis 1 : [[0 1 4 5] [2 3 6 7]] After flattening : [0 1 2 3 4 5 6 7]
示例 3:附加不同维度的数组
append()
方法可以附加不同维度的数组。但是,类似的 concatenate()
方法则不能。
让我们看一个例子。
import numpy as np
# create 2 arrays with different dimensions
a = np.array([1, 2, 3])
b = np.array([[4, 5], [6, 7]])
# append b to a using np.append()
c = np.append(a,b)
print(c)
# concatenate a and b using np.concatemate()
c = np.concatenate((a, b))
print(c)
输出
[1 2 3 4 5 6 7] ValueError: all the input arrays must have the same number of dimensions
注意: numpy.append()
比 np.concatenate()
更灵活,因为它可以将标量或一维数组附加到高维数组。但是,在处理形状相同的数组时,np.concatenate()
的内存效率更高。