NumPy AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’

Updated: February 21, 2024 By: Guest Contributor Post a comment

About the Error

When working with the NumPy library in Python, encountering errors is a common part of the development process. One such error is AttributeError: 'numpy.ndarray' object has no attribute 'append'. This error occurs because NumPy arrays, represented as numpy.ndarray, do not have an append method like conventional Python lists. This guide explores the reasons behind this error and proposes several solutions to address it.

Solution 1: Use NumPy’s numpy.concatenate()

The numpy.concatenate() function is a powerful tool that enables you to join two or more arrays along an existing axis.

  1. Ensure both arrays to be concatenated are NumPy arrays.
  2. Invoke the numpy.concatenate() function with the arrays as arguments.
  3. Specify the axis if necessary. The default axis is 0.

Example:

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.concatenate((arr1, arr2))
print(result)

Output:

[1, 2, 3, 4, 5, 6]

Solution 2: Use NumPy’s numpy.append()

Unlike the non-existent append method on NumPy arrays, the numpy.append() function allows you to add elements to the end of an array. It should be noted that numpy.append() returns a new array and does not modify the original array in place.

  1. Define or specify the array you want to append to.
  2. Specify the value(s) you wish to append.
  3. Call the numpy.append() function with the array and value(s) as arguments.

Example:

import numpy as np
arr = np.array([1, 2, 3])
new_arr = np.append(arr, [4, 5, 6])
print(new_arr)

Output:

[1, 2, 3, 4, 5, 6]

Solution 3: Convert to Lists, Append, Convert Back

As a workaround, you can convert the NumPy array to a conventional Python list, use the native append() or extend() methods for lists, and then convert the list back to a NumPy array. This method is straightforward but may not be as efficient as using NumPy-built solutions for larger datasets.

  1. Convert the NumPy array to a list using the tolist() method.
  2. Use the append() or extend() methods on the list.
  3. Convert the list back to a NumPy array using np.array().

Example:

import numpy as np
arr = np.array([1, 2, 3])
list_arr = arr.tolist()
list_arr.append(4)
list_arr.extend([5, 6])
arr = np.array(list_arr)
print(arr)

Output:

[1, 2, 3, 4, 5, 6]

Notes on Solutions

Choosing the right solution depends on your specific requirements and the size of the dataset you’re working with. numpy.concatenate() and numpy.append() are more suited for NumPy-centric workflows and maintain the advantages of NumPy’s performance optimizations. The list conversion method can be simpler for those more comfortable with Python’s native list operations, but it may not be as efficient for larger data. It’s also important to remember that numpy.append() returns a new array, which can impact memory usage for very large arrays.