Учимся работать с функцией append в библиотеке numpy
numpy.append
numpy.append is a function in the NumPy library that allows you to add elements to the end of an array. It provides a convenient way to perform array extension operations without the need to create a new array or copy the old one.
Usage format of the append function:
numpy.append(arr, values, axis=None)
arr: the original array to which the values will be added.values: the values to be added to the array.axis: an optional parameter indicating the axis along which the addition should be performed. If the parameter is not specified, the array will be treated as one-dimensional.
Let's consider a few code examples to better understand how to work with the append function:
Example 1: Adding values to a one-dimensional array
import numpy as np
arr = np.array([1, 2, 3])
values = np.array([4, 5, 6])
new_arr = np.append(arr, values)
print(new_arr)
Output:
[1 2 3 4 5 6]
In this example, we declare a one-dimensional array arr with elements [1, 2, 3] and an array values with elements [4, 5, 6]. Then we use the append function to add the values from values to the end of the arr array, and save the result in a new array new_arr. Finally, we print new_arr, which will contain all the values from both arrays.
Example 2: Adding values to a two-dimensional array
import numpy as np
arr = np.array([[1, 2], [3, 4]])
values = np.array([[5, 6]])
new_arr = np.append(arr, values, axis=0)
print(new_arr)
Output:
[[1 2]
[3 4]
[5 6]]
In this example, we have a two-dimensional array arr with a size of 2x2 and an array values with a size of 1x2. We use the append function with the axis=0 parameter to add the values array to the end of the arr array vertically. The result is saved in a new array new_arr, which will have a size of 3x2. We print new_arr, which will show the concatenated result.
Example 3: Adding values to a three-dimensional array
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
values = np.array([[[13, 14, 15], [16, 17, 18]]])
new_arr = np.append(arr, values, axis=0)
print(new_arr)
Output:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]
[[13 14 15]
[16 17 18]]]
In this example, we have a three-dimensional array arr with a size of 2x2x3 and an array values with a size of 1x2x3. Using the append function with the axis=0 parameter, we add the values array to the end of the arr array vertically. The result is saved in a new array new_arr, which will have a size of 3x2x3. We print new_arr, and it will show that the values are successfully added to the end of the original array.
Thus, the append function in the NumPy library provides a convenient and efficient way to add elements to arrays. It allows you to avoid creating new arrays or copying old ones, making it a useful tool when working with large amounts of data.