Python 迭代 Numpy 矩阵行以分别应用一个函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16468717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over Numpy matrix rows to apply a function each?
提问by erogol
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 ?
我希望能够遍历矩阵以将函数应用于每一行。我怎样才能为 Numpy 矩阵做到这一点?
采纳答案by Saullo G. P. Castro
Use numpy.apply_along_axis(). Assuming your matrix is 2D, you can use like:
使用numpy.apply_along_axis(). 假设你的矩阵是二维的,你可以使用:
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]
回答by matthew-parlette
While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:
虽然您当然应该提供更多信息,但如果您试图遍历每一行,则可以使用 for 循环进行迭代:
import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
print str(row)
回答by hamster ham
Here's my take if you want to try using multiprocesses to process each row of numpy array,
如果您想尝试使用多进程来处理 numpy 数组的每一行,这是我的看法,
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.
pool.map 接受一个函数和一个可迭代对象。
我使用“map”函数在数组的每一行上创建一个迭代器。
也许有更好的方法来创建可迭代对象。

