我需要将函数应用于numpy数组的每一列。我不能为数组的每个元素执行此操作,但它必须是每个列,因为每个列组合在一起代表一个信息。
C2 = [ np.sum( C[ :, i ] ) for i in range( 0, 30) ]
这是最有效的方法吗(为了说明我使用的是np.sum):
{{1}}
阵列C是500x4000,我也在为每一列应用耗时的功能。
答案 0 :(得分:3)
您可以尝试np.apply_along_axis
:
In [21]: A = np.array([[1,2,3],[4,5,6]])
In [22]: A
Out[22]:
array([[1, 2, 3],
[4, 5, 6]])
In [23]: np.apply_along_axis(np.sum, 0, A)
Out[23]: array([5, 7, 9])
In [24]: np.apply_along_axis(np.sum, 1, A)
Out[24]: array([ 6, 15])
答案 1 :(得分:1)
似乎需要大约75%的时间来使用它:
[ np.sum(row) for row in C.T ]
它也更像Pythonic。作为参考,这些是timeit
结果。
>>> timeit('[ np.sum( C[ :, i ] ) for i in range( 0, 30) ]',
setup='import numpy as np; C = np.random.normal(0, 1, (500, 30))', number=1000)
0.418906474798
>>> print timeit('[ np.sum(row) for row in C.T ]',
setup='import numpy as np; C = np.random.normal(0, 1, (500, 30))', number=1000)
0.345153254432
>>> print timeit('np.apply_along_axis(np.sum, 0, C)',
setup='import numpy as np; C = np.random.normal(0, 1, (500, 30))', number=1000)
0.732931300891