14.7 C
London
Tuesday, July 2, 2024
HomePythonFix Common Errors in PythonHow to Fix: ‘numpy.ndarray’ object has no attribute ‘append’

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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:

Additional Resources

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

How to Fix: No module named pandas
How to Fix: No module named numpy
How to Fix: columns overlap but no suffix specified

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories