Skip to content
Advertisement

Vectorize over the rows of an array

I have an array X and I want to apply a function f to all the rows of X:

# silly example
X = numpy.array([[1, 2, 3, 4, 5],
                 [6, 7, 8, 9, 0]], 'i')

def f(row): return sum(row)

y = numpy.vectorize(f, 'i')(rows(X))

Now, y should be array([15,30], 'i'). Which method or slicing magic will implement rows in the most efficient way?

Advertisement

Answer

NumPy implements the concept of “action over a particular axis”. The general function is numpy.apply_along_axis():

>>> numpy.apply_along_axis(sum, 1, X)
array([15, 30])

(where sum can of course be replaced by anything).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement