How to Append to Numpy Array

Numpy append() function merges two arrays and returns a new array, and the original array remains unchanged.

Append to numpy array

To append elements to a numpy array in Python, use the np.append() method. The np.append() is a numpy library function that appends values to the end of an array.

Syntax

numpy.append(array, values, axis = None)

Parameters

The np.append() function takes three arguments.

  1. array: It is an input array.
  2. values: To be appended to the array.
  3. axis: The axis along which the append operation is to be done. 

Return value

The np.append() function returns a copy of the array with values appended to the axis.

Example

import numpy as np

array_one = np.arange(4)
print("First array : ", array_one)
print("Shape : ", array_one.shape)

array_two = np.arange(7, 11)
print("\nSecond array : ", array_two)
print("Shape : ", array_two.shape)

array_final = np.append(array_one, array_two)
print("\nFinal Array : ", array_final)

Output

First array : [0 1 2 3]
Shape : (4,)

Second array : [ 7 8 9 10]
Shape : (4,)

Final Array : [ 0 1 2 3 7 8 9 10]

We appended the second array to the first one and returned the new one with combined values.

ValueError: all the input arrays must have same number of dimensions

The ValueError: all the input arrays must have same number of dimensions error occurs when you are trying to append an array to a different shape of the array. Both arrays should have the same shape.

import numpy as np

array_one = np.array([[21, 30],[19, 46]])
array_two = np.array([8, 9, 10, 11, 12])
 
final_array = np.append(array_one, array_two, axis=0)
print(final_array)

Output

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

And we are getting the ValueError because the input arrays did not have the same number of dimensions.

That’s it.

Related posts

np.concatenate

How to create empty numpy array

How to copy an array

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.