I have an array X
and I want to apply a function f
to all the rows of X
:
JavaScript
x
8
1
# silly example
2
X = numpy.array([[1, 2, 3, 4, 5],
3
[6, 7, 8, 9, 0]], 'i')
4
5
def f(row): return sum(row)
6
7
y = numpy.vectorize(f, 'i')(rows(X))
8
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()
:
JavaScript
1
3
1
>>> numpy.apply_along_axis(sum, 1, X)
2
array([15, 30])
3
(where sum
can of course be replaced by anything).