Apply a function to each row (row by row) of a NumPy array

So I have a function -

def function(x):
    x , y = vector
    return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2)

and say that I would like to evaluate it at the following points (the first column is the values ​​of x, and the second column is the values ​​of y) -

array([[-1.56113514,  4.51759732],
       [-2.80261623,  5.068371  ],
       [ 0.7792729 ,  6.0169462 ],
       [-1.35672858,  3.52517478],
       [-1.92074891,  5.79966161],
       [-2.79340321,  4.73430001],
       [-2.79655868,  5.05361163],
       [-2.13637747,  5.39255837],
       [ 0.17341809,  3.60918261],
       [-1.22712921,  4.95327158]])

i.e. I would like to pass the function to the first line of values ​​and evaluate, then the second line and evaluate, etc., And then the end result will be an array of values ​​evaluated at these points (so, an array of 10 values).

So, for example, if the function was, say, a two-dimensional normal distribution -

def function2(x):

function2 = (mvnorm.pdf(x,[0,0],[[1,0],[0,1]]))

return function2

and I passed the above values ​​to this function, I would get -

array([  1.17738907e-05,   1.08383957e-04,   1.69855078e-04,
         5.64757613e-06,   1.37432346e-05,   1.44032800e-04,
         1.33426313e-05,   1.97822328e-06,   6.56121709e-08,
         4.67076770e-05])

So basically, I'm looking for a way to rewrite a function so that it can do it. Moreover, I would like to save a function only as a function of one variable (i.e. only as a function of x).

Thank you for your help!

+7
2

np.apply_along_axis:

np.apply_along_axis(function, 1, array)

- , - , . . - , .

, apply_along_axis - apply_along_axis , . , . , . :

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

, , , - x y. x,y = vector , vector 2. (vector.shape = 2,...). , :

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

, , ( , , , ). , , , . disatvantage , .

+2

Source: https://habr.com/ru/post/1683391/


All Articles