Ошибка numpy ndarray object has no attribute append

Returns this error:
‘numpy.ndarray’ object has no attribute ‘append’

class1 = np.array([]) #creates 2 empty arrays
class2 = np.array([])

#yhat_tr is a vector(1 column, 100 rows) = numpy.ndarray
for i in yhat_tr: 
  if i < 0:
    class1.append([i]) #insert the iten in the array class1 or class2
  else:
    class2.append([i])

I want to insert new array itens inside the class1 or class2 arrays as soon the itens are evaluated inside the loop.
After that i will try to print the results in a scatter graphic with 2 colors where i can identify visually the class1 and class2 elements.

martineau's user avatar

martineau

119k25 gold badges165 silver badges297 bronze badges

asked Apr 20, 2019 at 17:21

Douglas's user avatar

4

You can add a NumPy array element by using the append() method of the NumPy module.

The syntax of append is as follows:

numpy.append(array, value, axis)

The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above.

The axis is an optional integer along which define how the array is going to be displayed. If the axis is not specified, the array structure will be flattened

answered Apr 20, 2019 at 18:04

Damiano C.'s user avatar

Damiano C.Damiano C.

2821 silver badge9 bronze badges

1

A quick look at the documentation shows that np.ndarray objects do not have a function append, it is a function of np itself:

class1 = np.append(class1, [i])

answered Apr 20, 2019 at 17:29

Alex's user avatar

AlexAlex

1831 silver badge10 bronze badges

0

As @Alex mentioned, numpy arrays dont have append method. You can use his suggestion to use numpy append method or You might want to define class variables as lists and use append and convert them to array after the loop as the code below does.

class1 = []
class2 = []

#yhat_tr is a vector(1 column, 100 rows) = numpy.ndarray
for i in yhat_tr: 
  if i < 0:
    class1.append([i]) #insert the iten in the array class1 or class2
  else:
    class2.append([i])

class1 = np.array(class1)
class2 = np.array(class2)

answered Apr 20, 2019 at 17:35

Moe's user avatar

MoeMoe

9712 gold badges10 silver badges24 bronze badges

Love how the famous Stackoverflow is so full of judgemental posters. Making this not much better than Facebook.

You need to up your game SO.

enter image description here

answered Aug 24, 2020 at 11:13

Rob's user avatar

RobRob

331 silver badge9 bronze badges

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться при использовании NumPy:

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

Эта ошибка возникает, когда вы пытаетесь добавить одно или несколько значений в конец массива NumPy с помощью функции append() в обычном Python.

Поскольку NumPy не имеет атрибута добавления, выдается ошибка. Чтобы исправить это, вы должны вместо этого использовать np.append() .

В следующем примере показано, как исправить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, мы пытаемся добавить новое значение в конец массива NumPy, используя функцию append() из обычного 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'

Мы получаем ошибку, потому что NumPy не имеет атрибута добавления.

Как исправить ошибку

Чтобы исправить эту ошибку, нам просто нужно вместо этого использовать np.append() :

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])

Используя np.append() , мы смогли успешно добавить значение «25» в конец массива.

Обратите внимание: если вы хотите добавить один массив NumPy в конец другого массива NumPy, лучше всего использовать функцию np.concatenate() :

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])

Обратитесь к онлайн-документации для подробного объяснения функций массива и конкатенации:

  • документация numpy.append()
  • документация numpy.concatenate()

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить: нет модуля с именем pandas
Как исправить: нет модуля с именем numpy
Как исправить: столбцы перекрываются, но суффикс не указан

NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. If you are into analytics, you might have come across this library in python. In the beginning, some things might confuse a programmer when switching from python traditional lists to NumPy arrays. One such error that we might come across is “AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’“.  In this article, let us look at why do we see this error and how to fix it.

When adding an item to a python list, we make use of the list’s append method. The syntax is pretty simple and when we try to replicate the same on a NumPy array we get the above-mentioned error. Let us look through it with an example.

Example: Code that depicts the error

Python

import numpy

print("-"*15, "Python List", "-"*15)

pylist = [1, 2, 3, 4]

print("Data type of python list:", type(pylist))

pylist.append(5)

print("After appending item 5 to the pylist:", pylist)

print("-"*15, "Numpy Array", "-"*15)

nplist = numpy.array([1, 2, 3, 4])

print("Data type of numpy array:", type(nplist))

nplist.append(5)

Output:

Numpy Append Error

In the above output, we can see that the python list has a data type of list. When we perform the append operation, the item i.e., 5 gets appended to the end of the list `pylist`. While we try the same method for the NumPy array, it fails and throws an error “AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’“. The output is pretty explanatory, the NumPy array has a type of numpy.ndarray which does not have any append() method. 

Now, we know that the append is not supported by NumPy arrays then how do we use it? It is actually a method of NumPy and not its array, let us understand it through the example given below, where we actually perform the append operation on a numpy list.

Syntax:

numpy.append(arr, values, axis=None)

Parameters:

  • arr: numpy array: The array to which the values are appended to as a copy of it.
  • values: numpy array or value: These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.
  • axis: int, optional: The axis along which values are appended. If axis is not given, both arr and values are flattened before use.

Example: Fixed code 

Python

import numpy

nplist = numpy.array([1, 2, 3, 4])

print("Data type of numpy array:", type(nplist))

print("Initial items in nplist:", nplist)

nplist = numpy.append(nplist, 5)

print("After appending item 5 to the nplist:", nplist)

Output:

Numpy Append Output

As in the output, we can see that initially, the NumPy array had 4 items (1, 2, 3, 4). After appending 5 to the list, it is reflected in the NumPy array. This is so because here the append function is used on NumPy and not on NumPy array object (numpy.ndarray). 

Last Updated :
28 Nov, 2021

Like Article

Save Article


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:

  • numpy.append() documentation
  • numpy.concatenate() documentation

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

In regular Python, you can use the append() method to add an item to the end of a list. You cannot use this method in NumPy. If you try to use the Python append() method to add an item to the end of a NumPy array, you will see the AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’ error.

This guide discusses in detail the cause of and the solution to this NumPy error. We will refer to an example to illustrate how to fix this error. Let’s get started.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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

The AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’ error is caused by using the append() method to add an item to a NumPy array. You should instead use the numpy.append() method if you want to add an item to a list.

The numpy.append() method was specifically written for the NumPy library. NumPy arrays are different to regular Python arrays so it is reasonable that NumPy has its own method to add an item to an array.

The NumPy append() method uses this syntax:

numpy.append(list_to_add_item, item_to_add)

The two parameters we will focus on are:

  • list_to_add_item: The list to which you want to add an item.
  • item_to_add: The item you want to add to the list you specify.

The numpy.append() method returns a new array which contains your specified item at the end, based on the “list_to_add_item” array. Note that you do not put append() after the list to which you want to add an item, like you would in regular Python.

Let’s go through an example of this error.

An Example Situation

We are building an application that tracks the performance grades a product has received after quality assurance at a factory. The products are scored on a scale of 50 and all products must achieve a score of at least 40 to go out into the world.

We are building the part of the application that adds new scores to an array which stores the scores a product has received for the last day. To build this program, we can use the append() method:

import numpy as np

scores = np.array([49, 48, 49, 47, 42, 48, 46, 50])
to_add = 49

scores.append(to_add)

print(scores)

Our program adds the score 39 to our list of scores. In a real-world situation, we may read these scores from a file, but to keep our example simple we have declared an array in our program. Our code prints a list of all the scores to the Python console after the new score is added to our array of scores.

Let’s run our code and see what happens:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
	scores.append(to_add)
AttributeError: 'numpy.ndarray' object has no attribute 'append'

Our code returns an error.

The Solution

We are trying to use the regular Python append() method to add an item to our NumPy array, instead of the custom-build numpy.append() method.

To solve this error, we need to use the syntax for the numpy.append() method:

import numpy as np

scores = np.array([49, 48, 49, 47, 42, 48, 46, 50])

scores = np.append(scores, 49)

print(scores)

We use the np term to refer to the NumPy library. This works because we defined the numpy library as np in our import statement. We pass the list to which we want to add an item as our first argument; the new score to add to our array is our second argument.

We have to assign the result of our np.append() operation to a new value. This is because np.append() does not modify an existing array. Instead, the method creates a new array with your new value added.

Let’s run our program and see what happens:

[49 48 49 47 42 48 46 50 49]

The number 49 has been successfully added to the end of our list.

Conclusion

The AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’ error indicates you are using the regular Python append() method to add an item to a NumPy array. Instead, you should use the numpy.append() method, which uses the syntax: numpy.append(list, item_to_add). This method creates a new list with the specified item added at the end.

Do you want to learn more about coding in NumPy? Check out our How to Learn NumPy guide. This guide contains top tips on how to build your knowledge of NumPy, alongside a list of learning resources suitable for beginner and intermediate developers.

  • Ошибка numpy float64 object is not callable
  • Ошибка nullreferenceexception как исправить
  • Ошибка nullreferenceexception object reference not set to an instance of an object
  • Ошибка nullpointerexception java что это
  • Ошибка null при обновлении iphone 6s что означает