Home > Net >  How to iterate over a numpy array, getting two values per loop?
How to iterate over a numpy array, getting two values per loop?

Time:01-14

I envision something like

import numpy as np
x = np.arange(10)
for i, j in x:
     print(i,j)

and get something like

0 1
2 3
4 5
6 7
8 9

But I get this traceback:

Traceback (most recent call last):
  File "/home/andreas/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/223.8214.51/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
TypeError: cannot unpack non-iterable numpy.int64 object

I also tried to use np.nditer(x) and itertools with zip(x[::2], x[1::2]), but that does not work either, with different error messages.

This should be super simple, but I can't find solutions online.

CodePudding user response:

You were trying to put 0 into i and j which is not possible. To achieve that result you'll have to reshape your numpy array using either x = x.reshape((5,2)) or x.shape = 5, 2. Then you can unpack it like that.

To visualize, this is what your current code is doing:

i, j = 0
...
i, j = 1
...

And this is what will happen if you reshape it:

i, j = [0, 1]
...
i, j = [2, 3]
...

CodePudding user response:

import numpy as np
x = np.arange(10)
c=0  #counter to print even occurence
for i in range(len(x)-1):
    c =1
    if c%2!=0:
        print(x[i],x[i 1])

#output
0 1
2 3
4 5
6 7
8 9

Just to make you understand, if I do not put a counter and I try to print an element and next element I will get repeating values like:

import numpy as np
x = np.arange(10)
for i in range(len(x)-1):
    print(x[i],x[i 1])

#output
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

CodePudding user response:

Trying to be faithful to the original attempt. zipping tuples of pairs of even and odds:

import numpy as np
x = np.arange(10)

for i, j in zip(x[::2], x[1::2]):
     print(i,j)

CodePudding user response:

Is it what you want?

for x in range(0,10,2):
    print(x, x 1)

or your values are maintained in the numpy array x, then

for i in range(0, len(x), 2):
    print(x[i],x[i 1])
  • Related