Iterating over Numpy matrix rows to apply a function each?

PythonMatrixNumpy

Python Problem Overview


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 ?

Python Solutions


Solution 1 - Python

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]

Solution 2 - Python

While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:

import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
  print str(row)

Solution 3 - Python

Here's my take if you want to try using multiprocesses to process each row of numpy array,

from multiprocessing import Pool
import numpy as np

def my_function(x):
    pass     # do something and return something

if __name__ == '__main__':    
    X = np.arange(6).reshape((3,2))
    pool = Pool(processes = 4)
    results = pool.map(my_function, map(lambda x: x, X))
    pool.close()
    pool.join()

pool.map take in a function and an iterable.
I used 'map' function to create an iterator over each rows of the array.
Maybe there's a better to create the iterable though.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionerogolView Question on Stackoverflow
Solution 1 - PythonSaullo G. P. CastroView Answer on Stackoverflow
Solution 2 - Pythonmatthew-parletteView Answer on Stackoverflow
Solution 3 - Pythonhamster hamView Answer on Stackoverflow