Python中的numpy.append()
时间:2020-02-23 14:42:20 来源:igfitidea点击:
Python numpy append()函数用于合并两个数组。
该函数返回一个新数组,原始数组保持不变。
NumPy append()语法
函数语法为:
numpy.append(arr, values, axis=None)
arr可以是类似数组的对象或者NumPy数组。
这些值将附加到此数组的副本中。这些值是类似数组的对象,并附加在" arr"元素的末尾。
该轴指定沿其附加值的轴。
如果未提供轴,则将两个阵列展平。
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]]
当将2×2数组沿x轴合并时,输出数组大小为4×2。
当2×2数组沿y轴合并时,输出数组大小为2×4。
3.合并不同形状的数组
如果两个数组的形状都不同(轴除外),则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)
在第一个示例中,将数组元素展平。
因此,即使它们的大小完全不同-1×2和2×3,append()也可以正常工作。在第二示例中,阵列形状是1×2和2×2。
由于我们沿0轴追加,因此0轴的形状可以不同。
其他形状应该相同,因此此append()也可以正常工作。
输出:
[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 >>>
Python numpy append()ValueError
阵列形状为1×2和2×3。
由于1轴的形状不同,因此会引发ValueError。