本文共 3372 字,大约阅读时间需要 11 分钟。
append() function is used to merge two arrays. This function returns a new array and the original array remains unchanged.
append()函数用于合并两个数组。 该函数返回一个新数组,原始数组保持不变。
The function syntax is:
函数语法为:
numpy.append(arr, values, axis=None)
Let’s look at some examples of NumPy append() function.
让我们来看一些NumPy append()函数的示例。
import numpy as nparr1 = np.array([[1, 2], [3, 4]])arr2 = np.array([[10, 20], [30, 40]])# no axis provided, array elements will be flattenedarr_flat = np.append(arr1, arr2)print(arr_flat) # [ 1 2 3 4 10 20 30 40]
import numpy as nparr_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}')
Output:
输出:
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]]
The append() function throws ValueError if both the arrays are of different shape, excluding the axis.
如果两个数组的形状均不同(轴除外),则append()函数将引发ValueError。
Let’s understand this scenario with a simple example.
让我们用一个简单的例子来了解这种情况。
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)
Output:
输出:
[1 2 1 2 3 1 2 3][[1 2] [1 2] [3 4]]
Let’s look at another example where ValueError will be raised.
让我们看另一个将引发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>>>
The array shapes are 1×2 and 2×3. Since the axis-1 shapes are different, ValueError is raised.
阵列形状为1×2和2×3。 由于1轴的形状不同,因此会引发ValueError。
Reference:
参考 :
翻译自:
转载地址:http://cclzd.baihongyu.com/