![]() |
VOOZH | about |
Let us see how to append values at the end of a NumPy array. Adding values at the end of the array is a necessary task especially when the data is not fixed and is prone to change. For this task, we can use numpy.append() and numpy.concatenate(). This function can help us to append a single value as well as multiple values at the end of the array. In this article, we will also see how to append elements to the NumPy array.
Below are the ways by which we can append values at the end of a NumPy Array in Python:
numpy.concatenateFor a 1D array, using the axis argument is not necessary as the array is flattened by default.
Output:
Original Array : [1 8 3 3 5]
Array after appending : [1 8 3 3 5 7]
You may pass a list or an array to the append function, the result will be the same.
Output:
First array is : [1 2 3]
Second array is : [4 5 6]
Array after appending : [1 2 3 4 5 6]
In this example, two 2D arrays, arr1 and arr2, are vertically stacked using np.concatenate() along the 0th axis, resulting in a combined 2D array.
Output:
[[1 2]
[3 4]
[5 6]]
In this example, a 1D integer array arr and a 1D float array arr_float are appended together using np.append(), resulting in an upcasted float array as the output.
Output:
[1. 2. 3. 4. 5.]
numpy.concatenateIn this example, multiple arrays, including arr and two arrays from values_to_append, are concatenated using list comprehension and np.concatenate(), producing a single combined array.
Output:
[1 2 3 4 5 6 7 8 9]
It is important that the dimensions of both the array matches otherwise it will give an error.
Output:
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]]