Numpy: How to map f: (shape (3) ndarray) --> (float) over an ndarray of shape (...,3) to get ndarray of shape (...)?
I have an function that maps an ndarray of shape (3) to a float, and I have an ndarray of shape (...,3). What's the best way to map that function over that array to 开发者_运维百科get an array of shape (...)?
Thanks.
You want numpy.apply_along_axis
.
def f(a):
return a[0] + a[1] + a[2]
mm = numpy.random.randn(5, 3)
numpy.apply_along_axis(f, 1, mm)
output: array([-1.75875289, -0.34689792, 0.66092486, -0.21626001, -0.14125476])
精彩评论