AttributeError: 'numpy.int32' object has no attribute 'append'
Solution 1
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.
Solution 2
this is numpy solution to your problem
x = np.array(x)
unique = np.unique(x)
[np.where(x == unique_num) for unique_num in unique]
Solution 3
You reassign your variable a
:
In the first line a=[]
, but you use again a
in ss generator:
ss=set([i for i in x if sum([1 for
a in x if a == i]) > 1])
Simple example:
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
9
>>>
Comments
-
Sayantan Mukherjee almost 2 years
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
-
Sayantan Mukherjee over 8 yearsoops sorry...got you. Let me check. Thanks a lot
-
Sayantan Mukherjee over 8 yearsoops sorry...got you. Let me check. Thanks a lot