迭代numpy矩阵列

时间:2017-02-05 09:41:55

标签: python numpy matrix

我有以下numpy矩阵:

        0      1      2      3      4      5      6      7      8      9      
0       0.0    1.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0   
1       0.0    0.0    5.0    0.0    9.0    0.0    0.0    0.0    0.0    0.0   
2       0.0    0.0    0.0    0.0    0.0    0.0    2.0    0.0    0.0    0.0   
3       0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    5.0    0.0   
4       0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0   
5       0.0    0.0    7.0    0.0    1.0    0.0    0.0    0.0    0.0    0.0   
6       0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0   
7       5.0    0.0    0.0    0.0    0.0    0.0    0.0    6.0    0.0    0.0   
8       2.0    0.0    0.0    0.0    3.0    0.0    6.0    0.0    8.0    0.0   
9       0.0    0.0    1.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0   
10      0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0    0.0   

我想分别计算每行和每列的非零值。所以我的结果应该是这样的:

average_rows = [1.0,7.0,2.0,5.0,0.0,4.0,0.0,5.5,4.75,1.0,0.0]
average_cols = [3.5,1.0,4.33333,0.0,4.33333,0.0,4.0,6.0,6.5,0.0]

我无法弄清楚如何迭代它们,并且我不断获得TypeError: unhashable type

此外,我不确定迭代是否是最佳解决方案,我也尝试使用R[:,i]来抓取每一列并使用sum(R[:,i])对其进行求和,但仍然会遇到相同的错误。

1 个答案:

答案 0 :(得分:1)

最好使用2d np.array而不是矩阵。

import numpy as np
data = np.array([[1, 2, 0], [0, 0, 1], [0, 2, 4]], dtype='float')
data[data == 0] = np.nan
# replace all zeroes with `nan`'s to skip them
# [[  1.   2.  nan]
# [ nan  nan   1.]
# [ nan   2.   4.]]
np.nanmean(data, axis=0)
# array([ 1. ,  2. ,  2.5])
np.nanmean(data, axis=1)
# array([ 1.5,  1. ,  3. ])