在 NumPy 数组的末尾附加值
让我们看看如何在 NumPy 数组的末尾附加值。在数组末尾添加值是一项必要的任务,尤其是当数据不固定且容易更改时。对于这个任务,我们可以使用 numpy.append()。这个函数可以帮助我们在数组末尾追加单个值以及多个值。
Syntax : numpy.append(array, values, axis = None)
Parameters :
- array : Input array.
- values : values to be added in the array.
- axis : Axis along which we want to insert the values.
Returns : An copy of array with values being appended at the end as per the mentioned object
along a given axis.
示例 1:将单个值附加到一维数组。对于一维数组,不需要使用轴参数,因为默认情况下数组是展平的。
# importing the module
import numpy as np
# creating an array
arr = np.array([1, 8, 3, 3, 5])
print('Original Array : ', arr)
# appending to the array
arr = np.append(arr, [7])
print('Array after appending : ', arr)
输出 :
Original Array : [1 8 3 3 5]
Array after appending : [1 8 3 3 5 7]
示例 2:在一维数组的末尾附加另一个数组。您可以将列表或数组传递给 append函数,结果将是相同的。
# importing the module
import numpy as np
# creating an array
arr1 = np.array([1, 2, 3])
print('First array is : ', arr1)
# creating another array
arr2 = np.array([4, 5, 6])
print('Second array is : ', arr2)
# appending arr2 to arr1
arr = np.append(arr1, arr2)
print('Array after appending : ', arr)
输出 :
First array is : [1 2 3]
Second array is : [4 5 6]
Array after appending : [1 2 3 4 5 6]
示例 3:在 n 维数组的末尾附加值。重要的是两个数组的尺寸都匹配,否则会出错。
# importing the module
import numpy as np
# create an array
arr = np.arange(1, 13).reshape(2, 6)
print('Original Array')
print(arr, '\n')
# create another array which is
# to be appended column-wise
col = np.arange(5, 11).reshape(1, 6)
print('Array to be appended column wise')
print(col)
arr_col = np.append(arr, col, axis = 0)
print('Array after appending the values column wise')
print(arr_col, '\n')
# create an array which is
# to be appended row wise
row = np.array([1, 2]).reshape(2, 1)
print('Array to be appended row wise')
print(row)
arr_row = np.append(arr, row, axis = 1)
print('Array after appending the values row wise')
print(arr_row)
输出 :
Original Array
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Array to be appended column wise
[[ 5 6 7 8 9 10]]
Array after appending the values column wise
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[ 5 6 7 8 9 10]]
Array to be appended row wise
[[1]
[2]]
Array after appending the values row wise
[[ 1 2 3 4 5 6 1]
[ 7 8 9 10 11 12 2]]
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。