Search code examples
pythonloopsnumpy-ndarrayniftinipype

Iterating over the number of axes of a 4D numpy array


this is probably very simple and I'm just overlooking something but here you go:

I have a 4D array in shape: (x,y,z,t)

How do i iterate over the number of axis of that array wit a for-loop? Not along a single axis but once for every axis?

Something like this:

for a in range(data.shape):
            data_20 = np.percentile(data_20, 80, axis=a, keepdims=True)

Thanks!


Solution

  • To iterate over range of dimensions of a numpy.array use .ndim

    Code:

    # convert data to numpy.array if data is a list
    
    for i in range(np.array(data).ndim):
        print(i)
    

    Output:

    0
    1
    2
    3