Difficulties to understand np.nditer

Viewed 27

I am very new to python. I want to clearly understand the below code, if there's anyone who can help me.

Code: import numpy as np

arr = np.array([[1, 2, 3, 4,99,11,22], [5, 6, 7, 8,43,54,22]])

for x in np.nditer(arr[0:,::4]):

  print(x)

My understanding:

  1. This 2D array has two 1D arrays.
  2. np.nditer(arr[0:,::4]) will give all value from 0 indexed array to upto last array, ::4 means the gap between printed arrays will be 4.

Question:

  1. Is my understanding for no 2 above correct?
  2. How can I get the index for the print(x)? Because of the step difference of 4 e.g [0:,::4] or any gap [0:,::x] I want to find out the exact index that it is printing. But how?
1 Answers

Addressing your questions below

  1. Yes, I think your understanding is correct. It might help to first print what arr[0:,::4] returns though:
iter_array = arr[0:,::4]
print(iter_array)
>>> [[ 1 99]
>>>  [ 5 43]]

The slicing takes out each 4th index of the original array. All nditer does is iterate through these values in order. (Quick FYI: arr[0:] and arr[:] are equivalent, since the starting point is 0 by default).

  1. As you pointed out, to get the index for these you need to keep track of the slicing that you did, i.e. arr[0:, ::x]. Remember, nditer has nothing to do with how you sliced your array. I'm not sure how to best get the indices of your slicing, but this is what I came up with:
import numpy as np

ls = [
    [1, 2, 3, 4,99,11,22],
    [5, 6, 7, 8,43,54,22]
]

arr = np.array(ls)
inds = np.array([
    [(ctr1, ctr2) for ctr2, _ in enumerate(l)] for ctr1, l in enumerate(ls)
]) # create duplicate of arr filled with zeros

step = 4
iter_array = arr[0:,::step]
iter_inds = inds[0:,::step]

print(iter_array)
>>> [[ 1 99]
>>>  [ 5 43]]
print(iter_inds)
>>> [[[0 0]
>>>   [0 4]]
>>> 
>>>  [[1 0]
>>>   [1 4]]]

All that I added here was an inds array. This array has elements equal to their own index. Then, when you slice both arrays in the same way, you get your indices. Hopefully this helps!

Related