(SOLVED) numpy.ndarray object has no attribute append

The numpy.ndarray object has no attribute append is an error message that occurs when you are trying to call the append method on the array numpy, and does not have any attribute. This numpy array is a fixed-sized array and does not have an append method just like the Python list does.

For instance, if you want to add elements to the numpy array, you can easily use the function name numpy.append, or else you can index the array and reassign the values.

Example:

import numpy as np

x = np.array([10, 20, 30])

# using np.append
y = np.append(x, [40, 50, 60])
print(y)

# using indexing
c = np.zeros(6, dtype=int)
c[:len(x)] = x
c[len(x):] = [40, 50, 60]
print(c)

Output:

[10 20 30 40 50 60]
[10 20 30 40 50 60]

How to fix this error?

To solve or fix this error ‘numpy.ndarray’ object has no attribute ‘append’, you just need to use the other method for adding elements to the array numpy.

The following are the alternatives to append the method:

  • Using numpy.append
import numpy as np

x = np.array([10, 20, 30])
y = np.append(x, [40, 50, 60])
print(y)
  • Using indexing and reassignment
import numpy as np

x = np.array([10, 20, 30])
y = np.zeros(6, dtype=int)
y[:len(x)] = x
y[len(x):] = [40, 50, 60]
print(y)
  • Using numpy.concatenate
import numpy as np

x = np.array([10, 20, 30])
y = np.concatenate((x, [40, 50, 60]))
print(y)

The three methods will produce the same output: [10 20 30 40 50 60]

How to reproduce the error?

To reproduce the error attributeerror: numpy.ndarray object has no attribute append by trying to numpy append and call the method in the numpy array.

import numpy as np

x = np.array([1, 2, 3])
x.append(4)

When you run the code, you will see an error message below.

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

Conclusion

I hope this article has helped you solve your problem about the numpy.ndarray object has no attribute append. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.

Leave a Comment