numpy:矩阵中每一行的不同子集的平均值

问题描述 投票:0回答:1

给出以下矩阵

In [1]: a
Out[1]: 
array([[106.74    , 108.072   , 108.72    , 109.584   , 108.468   ],
       [114.012   , 114.156   , 107.928   , 113.904   , 112.968   ],
       [114.396225, 115.21124 , 116.01796 , 115.0901  , 113.01843 ]],
      dtype=float32)

我可以像这样计算行的每个子集的平均值,

In [2]: np.mean(a[:,1:3],axis=1)
Out[2]: array([108.395996, 111.042   , 115.6146  ], dtype=float32)

但是我现在想做的是,以下,

给定一组索引i = [3,4,3]

我想有能力

a[0,1:3]

a[1,1:4]

a[3,1:2]

分别是

所以,自然地,我的第一次尝试是,

In [2]: np.mean(a[:,1:i],axis=1)
TypeError: slice indices must be integers or None or have an __index__ method

这肯定行不通。

我也知道这一点,

In [3]: a[np.where(i)+(i,)]
Out[3]: array([108.468 , 113.904 , 115.0901], dtype=float32)

但是我没办法找出将它们结合起来的方法...。

有什么想法吗?

python numpy subset
1个回答
0
投票

来自安德拉斯(Andras)的好主意,我也将使用相同的方法。面具可以用类似:

的东西建造
istart = np.array([1, 1, 1])
istop = np.array([3, 4, 3])

col = np.broadcast_to(np.arange(a.shape[1]), a.shape)
#array([[0, 1, 2, 3, 4],
#       [0, 1, 2, 3, 4],
#       [0, 1, 2, 3, 4]])

mask = (istart.reshape(-1, 1) <= col) & (col < istop.reshape(-1, 1))
#array([[False,  True,  True, False, False],
#       [False,  True,  True,  True, False],
#       [False,  True,  True, False, False]], dtype=bool)

(a * mask).sum(axis=1) / mask.sum(axis=1)

array([ 108.396 ,  111.996 ,  115.6146])
© www.soinside.com 2019 - 2024. All rights reserved.