If you plan to insert a value to the end of a numpy.ndarray, you will get an error: AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’. In this tutorial, we will introduce how to fix this error.
Here is an example:
import numpy as np data = np.array([1,2,3]) data.append(4)
Run this code, you will get the result:
Why does this attribute error occur?
Because there is no numpy.ndarray.append() funtion in numpy.ndarray.
How to fix this error?
We can use numpy.append() function.
numpy.append(arr, values, axis=None)
This function will append values to the end of an array.
As to example above, we can modify it to be:
import numpy as np data = np.array([1,2,3]) datax = np.append(data, 4) print(data) print(datax)
Run this code, you will get the result as:
[1 2 3] [1 2 3 4]
From the result we can find: The original numpy.ndarray data is not changed, numpy.append() function will return a new numpy.ndarray.
You will find this error is fixed.