NumPy append()

The append() method adds the values at the end of a NumPy array.

import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])

# append array2 to array1 array3 = np.append(array1, array2)
print(array3) # Output : [1 2 3 4 5 6]

append() Syntax

The syntax of append() is:

numpy.append(array, values, axis)

append() Arguments

The append() method takes three arguments:

  • array - original array
  • values - the array to be appended at the end of the original array
  • axis - the axis along which the values are appended

Note: If axis is None, the array is flattened and appended.


append() Return Value

The append() method returns a copy of the array with values appended.


Example 1: Append an Array

import numpy as np

array1 = np.array([0, 1, 2, 3])
array2 = np.array([4, 5, 6, 7])

# append values to an array array3 = np.append(array1, array2)
print(array3)

Output

[0 1 2 3 4 5 6 7]

Example 2: Append Array Along Different Axes

We can pass axis as the third argument to the append() method. The axis argument determines the dimension at which a new array needs to be appended (in the case of multidimensional arrays).

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])

# append array2 to array1 along axis 0 array3 = np.append(array1, array2, 0) # append array2 to array1 along axis 1 # specifying axis argument explicitly array4 = np.append(array1, array2, axis = 1) # append array2 to array1 after flattening array5 = np.append(array1, array2, None)
print('\nAlong axis 0 : \n', array3) print('\nAlong axis 1 : \n', array4) print('\nAfter flattening : \n', array5)

Output

Along axis 0 : 
[[0 1]
 [2 3]
 [4 5]
 [6 7]]

Along axis 1 : 
 [[0 1 4 5]
 [2 3 6 7]]

After flattening : 
 [0 1 2 3 4 5 6 7]

Example 3: Append Arrays of Different Dimensions

The append() method can append arrays of different dimensions. However, the similar method concatenate() can't.

Let's see an example.

import numpy as np

# create 2 arrays with different dimensions
a = np.array([1, 2, 3])
b = np.array([[4, 5], [6, 7]])

# append b to a using np.append() c = np.append(a,b) print(c) # concatenate a and b using np.concatemate() c = np.concatenate((a, b)) print(c)

Output

[1 2 3 4 5 6 7]
ValueError: all the input arrays must have the same number of dimensions 

Note: numpy.append() is more flexible than np.concatenate() as it can append a scalar or a 1D array to a higher-dimensional array. However, when dealing with arrays of the same shape, np.concatenate() is more memory efficient.