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 ?
60
votes
It is likely that you will get more helpful answers if you explain what you are trying to achieve / what kind of function to apply. Also, you may want to have a look at: stackoverflow.com/questions/8079061/…
- root
please post your code. If you haven't tried to do it yet, go try some stuff and post what problems you have
- Ryan Saxe
3 Answers
76
votes
64
votes
6
votes
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.