I want to iterate over a numpy array and do some calculations on the values. However, things are not as expected. To show what I mean, I simply wrote this code to read values from a numpy array and move them to another list.
a = array([1,2,1]).reshape(-1, 1)
u = []
for i in np.nditer(a):
print(i)
u.append(i)
print(u)
According to tutorial, nditer points to elements and as print(i) shows, i is the value. However, when I append that i to an array, the array doesn't store the value. The expected output is u = [1, 2, 1] but the output of the code is
1
2
1
[array(1), array(2), array(1)]
What does array(1) mean exactly and how can I fix that?
P.S: I know that with .tolist() I can convert a numpy array to a standard array. However, in that code, I want to iterate over numpy elements.
i, you would see that its of type<class 'numpy.ndarray'>arraywith one element in it.np.nditeron the first place?ato be an array of shape(3,1), which makes it a d=2 array, so each iteration will return a d=1 array. If you flatten it first, it will do the trick :for i in a.flatten(): u.append(i)iand thatprint(i)misguided me.