NumPy - append() function
The NumPy append() function is used to append values to the end of an array. The syntax for using this function is given below:
Syntax
numpy.append(arr, values, axis=None)
Parameters
arr |
Required. Specify the array to which the values to be appended. |
values |
Required. Specify the values to be appended. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use. |
axis |
Optional. Specify the axis along which values are appended. If axis is not given, both arr and values are flattened before use. |
Return Value
Returns a copy of array with values appended to axis.
Example: append values on axis=0
In the example below, values array is added on axis=0. Please note that the values array must have same shape as arr, excluding specified axis.
import numpy as np arr = np.ones((3,3)) values = np.array([[10, 20, 30],[40, 50, 60]]) print("Initial Array:") print(arr) print("\nReturned array after append:") print(np.append(arr, values, axis=0))
The output of the above code will be:
Initial Array: [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]] Returned array after append: [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 10. 20. 30.] [ 40. 50. 60.]]
Example: append values on axis=1
When the values array is added on axis=1, please note that the shape of values array.
import numpy as np arr = np.ones((3,3)) values = np.array([[10, 40], [20, 50], [30, 60]]) print("Initial Array:") print(arr) print("\nReturned array after append:") print(np.append(arr, values, axis=1))
The output of the above code will be:
Initial Array: [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]] Returned array after append: [[ 1. 1. 1. 10. 40.] [ 1. 1. 1. 20. 50.] [ 1. 1. 1. 30. 60.]]
Example: append values on axis=None
When axis is not specified or equal to None, arr and values array are flattened before appending. Consider the following example.
import numpy as np arr = np.ones((2,2)) values = np.array([10, 20, 30]) print("Returned array after append:") print(np.append(arr, values, axis=None))
The output of the above code will be:
Returned array after append: [ 1. 1. 1. 1. 10. 20. 30.]
❮ NumPy - Functions