Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over Numpy matrix rows to apply a function each?

I want to be able to iterate over the matrix to apply a function to each row. How can I do it for a Numpy matrix ?

like image 878
erogol Avatar asked May 09 '13 18:05

erogol


People also ask

Can you iterate over a NumPy array?

NumPy package contains an iterator object numpy. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python's standard Iterator interface.


1 Answers

You can use numpy.apply_along_axis(). Assuming that your array is 2D, you can use it like:

import numpy as np mymatrix = np.matrix([[11,12,13],                       [21,22,23],                       [31,32,33]]) def myfunction(x):     return sum(x)  print(np.apply_along_axis(myfunction, axis=1, arr=mymatrix)) #[36 66 96] 
like image 64
Saullo G. P. Castro Avatar answered Oct 02 '22 16:10

Saullo G. P. Castro