Solve the attributeerror: numpy.ndarray object has no attribute append error

In today’s Data Analysis tutorial we’ll solve a common issue that you might have encountered when trying to add new elements to a Numpy array.

Reproducing the error

Let’s see together how we can easily reproduce the error:

# import the numpy library
import numpy as np

#create a short numpy array
my_array = np.arange(10, 110, 10)

#print the array

This will return the following ndarray object:

[ 10  20  30  40  50  60  70  80  90 100]

Next we would like to add a couple of new elements of a list to the array. W e will try to use the append method:

my_array.append([120, 130])

This will fail with the following attribute error exception, screenshot taken from my Jupyter notebook (you will get the same error in PyCharm, VS COde, Spyder, Colab etc’):

Fix the attribute error no append in Numpy

As we saw above, we tried to use the Python append method on a numpy array. Append is used with Python lists, and is not available for numpy arrays.

You are able to get rid of the error in multiple ways:

  1. Using np.append to concatenate the list to the numpy array
my_array = np.append(my_array, [120, 130])
  1. Convert the list to an array and append
my_new_array = np.array([120,130])
my_array = np.append(my_array, my_new_array)
  1. Using np.concatenate
my_new_array = np.array([120,130])
my_array = np.concatenate((my_array, my_new_array))

All the above will render the same result – in our case, the following numpy array:

array([ 10,  20,  30,  40,  50,  60,  70,  80,  90, 100, 120, 130])

Related learning

How to encode a Python list the right way?