Skip to content Skip to sidebar Skip to footer

Iterating Over 3d Numpy Using One Dimension As Iterator Remaining Dimensions In The Loop

Despite there being a number of similar questions related to iterating over a 3D array and after trying out some functions like nditer of numpy, I am still confused on how the foll

Solution 1:

You should be able to iterate over the first dimension with a for loop:

for s in x_:
    sliding_window_plot(s)

with each iteration s will be the next array of shape (11, 300).

Solution 2:

In general for all nD-arrays where n>1, you can iterate over the very first dimension of the array as if you're iterating over any other iterable. For checking whether an array is an iterable, you can use np.iterable(arr). Here is an example:

In [9]: arr = np.arange(3 * 4 * 5).reshape(3, 4, 5) 

In [10]: arr.shape 
Out[10]: (3, 4, 5) 

In [11]: np.iterable(arr) 
Out[11]: True 

In [12]: for a in arr: 
    ...:     print(a.shape) 
    ...:                     
(4, 5)
(4, 5)
(4, 5)

So, in each iteration we get a matrix (of shape (4, 5)) as output. In total, 3 such outputs constitute the 3D array of shape (3, 4, 5)


If, for some reason, you want to iterate over other dimensions then you can use numpy.rollaxis to move the desired axis to the first position and then iterate over it as mentioned in iterating-over-arbitrary-dimension-of-numpy-array


NOTE: Having said that numpy.rollaxis is only maintained for backwards compatibility. So, it is recommended to use numpy.moveaxis instead for moving the desired axis to the first dimension.

Solution 3:

You are hardcoding the 0th slice outside the for loop. You need to create x_plot to be inside the loop. In fact you can simplify your code by not using x_plot at all.

for i in rangge(x_.shape[0]): sliding_window_plot(x_[i])

Post a Comment for "Iterating Over 3d Numpy Using One Dimension As Iterator Remaining Dimensions In The Loop"