Apply function on each row (row-wise) of a NumPy array Apply function on each row (row-wise) of a NumPy array python python

Apply function on each row (row-wise) of a NumPy array


You can use np.apply_along_axis:

np.apply_along_axis(function, 1, array)

The first argument is the function, the second argument is the axis along which the function is to be applied. In your case, it is the first axis. The last argument is the array, of course.


You should be warned, however, that apply_along_axis is only a convenience function, not a magic bullet. It has a severe speed limitation, since it just hides a loop. You should always try to vectorize your computation, where possible. Here's how I'd do this:

v = array[:, 0] ** 2   # computing just once  return np.exp((-v / 200) - 0.5 * (array[:, 1] + 0.05 * v - 5) ** 2)


There are several ways to accomplish this, the only line you have to change is the asignment of x and y. x,y = vector only works if the first dimension of vector has length 2. (vector.shape = 2,...). So you can simply change your vector with any of the following commands:

x,y = vector.T #transpose the arrayx,y = vector.swapaxes(0,1) #swap the axis 0 and 1x,y = np.rollaxis(vector,1) #roll the axis 1 to the frontx,y = vector[:,0], vector[:,1] #slice asignement

Just choose the one you like most, there might be other ways (I'm almost sure, but I guess this will suffice). The last one is by far the fastest, the others are comparable. The disatvantage of the last one however is, that it's not so easy to use it in higher dimensions.