Home > other >  Iterating over numpy array and access the values
Iterating over numpy array and access the values

Time:01-25

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.

CodePudding user response:

As already explained in your previous question, numpy.nditer yields numpy arrays. What is shown by print is only the representation of the object, not the content or type of the object (e.g., 1 and '1' have the same representation, not the same type).

import numpy as np
a = np.array([1,2,1]).reshape(-1, 1)

type(next(np.nditer(a)))
# numpy.ndarray

You just have a zero-dimensional array:

np.array(1).shape
# ()

There is no need to use numpy.nditer here. If you really want to iterate over the rows of your array with single column (and not use tolist), use:

u = []
for i in a[:,0]:
    u.append(i)
u
# [1, 2, 1]

CodePudding user response:

numpy.nditer actually returns a numpy array. If you want the actual value of this item, you can use the built in item() function:

a = array([1,2,1]).reshape(-1, 1)
u = []
for i in np.nditer(a):
    u.append(i.item())
print(u)

CodePudding user response:

A pure python equivalent of what's happening with your append is:

In [75]: alist = []
    ...: x = [0]
    ...: for i in range(3):
    ...:     x[0] = i
    ...:     print(x)
    ...:     alist.append(x)
[0]
[1]
[2]
In [76]: alist
Out[76]: [[2], [2], [2]]
In [77]: x
Out[77]: [2]

x is modified in each loop, but only a reference is saved. The result is that all elements of the list are the same object, and display its last value.

  •  Tags:  
  • Related