Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

First let me show what i want to do.
I have a matrix,

x = [1, 2, 1, 2, 3, 3, 2, 3, 1, 2]

All i want do is to select position of repeated numbers in the array and print it in a matrix x_new where :

x_new[0]= [0,2,8] (for similar position of repeated 1's in x)  
x_new[1]=[1,3,6,9](for similar position of repeated 2's in x)  
x_new[2]=[4,5,7] (for similar position of repeated 3's in x)

Until now what i have done is :

a=[]      
x=m[:,3]  #x=np.array([1, 2, 1, 2, 3, 3, 2, 3, 1, 2])     
ss=set([i for i in x if sum([1 for a in x if a == i]) > 1])     
lenss=len(ss)      
for ln in range(lenss):    
    for k in range(10):      
        if(x[k]== list(ss)[ln]):    
            print k     
        a.append(ln)    
    print 'next'    

But at the a.append line it's showing:

'numpy.int32' object has no attribute 'append'

Can anyone please tell me how to overcome this error? Thanks

like image 942
Sayantan Mukherjee Avatar asked Sep 08 '15 07:09

Sayantan Mukherjee


People also ask

How to fix AttributeError numpy ndarray object has no attribute append?

ndarray' object has no attribute 'append' occurs if you attempt to append an element into NumPy array using the regular append() method like we do in the list. The numpy. ndarray does not have an append method, and hence it throws AttributeError. We can resolve this error by using the numpy.

Has no attribute append Python?

The Python "AttributeError: 'NoneType' object has no attribute 'append'" occurs when we try to call the append() method on a None value, e.g. assignment from function that doesn't return anything. To solve the error, make sure to only call append() on list objects.


Video Answer


1 Answers

In Python 2.x , the variables you use inside list comprehension leak into the surrounding namespace, so the a variable you use in the list comprehension -

ss=set([i for i in x if sum([1 for a in x if a == i]) > 1])  

Changes the a variable you defined as list to elements of x.

Example for this -

>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> s = [i for i in range(5)]
>>> i
4

You should use different name inside the list comprehensin , and it would help if you use more meaningful names for your variables, that would reduce the risk of running into such issues.

This issue should not occur in Python 3.x , as in Python 3.x , list comphrehension has a namespace of its own.

like image 175
Anand S Kumar Avatar answered Sep 28 '22 10:09

Anand S Kumar