How to fix ‘numpy.ndarray’ object has no attribute ‘append’

The ‘numpy.ndarray’ object does not have an attribute called ‘append’, since it is not a list object and does not have the same methods as a list object. To fix this, you can use the ‘numpy.concatenate’ method to join two numpy arrays together, or you can convert the numpy array into a list object and then use the list object’s ‘append’ method.


One error you may encounter when using NumPy is:

AttributeError: 'numpy.ndarray' object has no attribute 'append'

This error occurs when you attempt to append one or more values to the end of a NumPy array by using the append() function in regular Python.

Since NumPy doesn’t have an append attribute, an error is thrown. To fix this, you must use np.append() instead.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we attempt to append a new value to the end of a NumPy array using the append() function from regular Python:

import numpy as np

#define NumPy array
x = np.array([1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23])

#attempt to append the value '25' to end of NumPy array
x.append(25)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

We receive an error because NumPy doesn’t have an append attribute.

How to Fix the Error

To fix this error, we simply need to use np.append() instead:

import numpy as np

#define NumPy array
x = np.array([1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23])

#append the value '25' to end of NumPy array
x = np.append(x, 25)

#view updated array
x

array([ 1,  4,  4,  6,  7, 12, 13, 16, 19, 22, 23, 25])

By using np.append() we were able to successfully append the value ’25’ to the end of the array.

Note that if you’d like to append one NumPy array to the end of another NumPy array, it’s best to use the np.concatenate() function:

import numpy as np

#define two NumPy arrays
a = np.array([1, 4, 4, 6, 7, 12, 13, 16, 19, 22, 23])
b = np.array([25, 26, 26, 29])

#concatenate two arrays together
c = np.concatenate((a, b))

#view resulting array
c

array([ 1,  4,  4,  6,  7, 12, 13, 16, 19, 22, 23, 25, 26, 26, 29])

Refer to the online documentation for an in-depth explanation of both the array and concatenate functions:

The following tutorials explain how to fix other common errors in Python:

x