apply a function on multiple dimension in numpy array

Viewed 60

I have a numpy array od dimension (343, 343, 250). It's an image time serie, with the first dim being x coordinate, 2nd dim y coordinate, and 3rd dim the date.

I try o apply a function on every pixel time serie as such:

def f(d):

   #do stuff with d
   return stuff

result = np.zeros((data.shape[0], data.shape[1]), dtype=cp.float32)
for i in range(data.shape[0]):
    for j in range(data.shape[1]:

        d = data[i,j,:]
        result[i,j] = f(d)

How could I do the same thing in a more numpy way (without the for loop) ?

1 Answers

Using numpy.apply_along_axis:

import numpy as np
result = np.apply_along_axis(f, axis=2, arr=data)
Related