在Python中,使用numpy.append()
Python的numpy库中的append()函数用于合并两个数组。该函数会返回一个新的数组,原始数组不会改变。
NumPy append() 语法
函数语法如下:
numpy.append(arr, values, axis=None)
- The arr can be an array-like object or a NumPy array. The values are appended to a copy of this array.
- The values are array-like objects and it’s appended to the end of the “arr” elements.
- The axis specifies the axis along which values are appended. If the axis is not provided, both the arrays are flattened.
Python的numpy.append()示例
让我们来看一些NumPy append() 函数的示例。
1. 将两个数组展开合并
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[10, 20], [30, 40]])
# no axis provided, array elements will be flattened
arr_flat = np.append(arr1, arr2)
print(arr_flat) # [ 1 2 3 4 10 20 30 40]
2. 沿轴向合并
import numpy as np
arr_merged = np.append([[1, 2], [3, 4]], [[10, 20], [30, 40]], axis=0)
print(f'Merged 2x2 Arrays along Axis-0:\n{arr_merged}')
arr_merged = np.append([[1, 2], [3, 4]], [[10, 20], [30, 40]], axis=1)
print(f'Merged 2x2 Arrays along Axis-1:\n{arr_merged}')
输出:
Merged 2x2 Arrays along Axis-0:
[[ 1 2]
[ 3 4]
[10 20]
[30 40]]
Merged 2x2 Arrays along Axis-1:
[[ 1 2 10 20]
[ 3 4 30 40]]
- When the 2×2 arrays are merged along the x-axis, the output array size is 4×2.
- When the 2×2 arrays are merged along the y-axis, the output array size is 2×4.
3. 合并不同形状的数组 de
如果两个数组的形状不同(轴除外),那么append()函数会抛出ValueError。让我们用一个简单的例子来理解这种情况。
arr3 = np.append([[1, 2]], [[1, 2, 3], [1, 2, 3]])
print(arr3)
arr3 = np.append([[1, 2]], [[1, 2], [3, 4]], axis=0)
print(arr3)
- In the first example, the array elements are flattened. So even if they have completely different size – 1×2 and 2×3, the append() works fine.
- In the second example, the array shapes are 1×2 and 2×2. Since we are appending along the 0-axis, the 0-axis shape can be different. The other shapes should be the same, so this append() will also work fine.
输出:
[1 2 1 2 3 1 2 3]
[[1 2]
[1 2]
[3 4]]
让我们看看另一个可能引发 ValueError 的例子。
>>> import numpy as np
>>>
>>> arr3 = np.append([[1, 2]], [[1, 2, 3]], axis=0)
Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numpy/lib/function_base.py", line 4528, in append
return concatenate((arr, values), axis=axis)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
>>>

数组的形状为1×2和2×3。由于轴1的形状不同,引发了ValueError错误。参考:API文档。