How to append numpy arrays

Share

numpy.append() is used to append values to the end of an array. It takes in the following arguments:

  • arr: values are attached to a copy of this array.

  • values: these values are appended to arr.

  • axis: this is an optional parameter that specifies the axis along with which values are appended. If the axis is not specified, then arr and values are flattened out.

numpy.append() does not alter the original array, instead, it returns a new array.

Take a look at the function signature below:

svg viewer

C​ode

In the first code snippet, the axis is not specified,​ so arr and values are flattened out.

import numpy as np
print(np.append([1, 2, 3], [['a', 'b', 'c'], [7, 8, 9]]))

In the following code snippet, values are appended along axis 1.

import numpy as np
print(np.append([[4, 5, 6]], [[7, 8, 9]], axis = 1))
# Try setting the axis to 0

For more details, refer to the official documentation.

Copyright ©2024 Educative, Inc. All rights reserved