Skip to main content
 首页 » 编程设计

python之使用坐标列表切片 numpy 数组

2025年05月04日16dflying

考虑一个形状为 (a,b,c) 的 numpy ndarray M 和一个坐标列表 [(b0,c0),( b1,c1),...,(bn,cn)].

我想要以下向量集合:[M[:,b0,c0],M[:,b1,c1],...,M[:,bn,cn]] . 我怎样才能通过列表理解实现这一目标?

编辑:我需要一个适用于任意数量维度的解决方案,即在这种情况下(比如)M.shape = (a,b,c,d) 和坐标 = [(b0,c0,d0),...,(bn,cn,dn)],以及更高维的情况。

请您参考如下方法:

您不想使用列表理解来执行此操作。 “花式索引”可以一次性完成所有事情。我建议:

inds = [(b0,c0),(b1,c1),...,(bn,cn)] 
 
#inds_array[0] = [b0, b1, b2, ...] 
inds_array = np.moveaxis(np.array(inds), -1, 0) 
 
M[np.index_exp[:] + tuple(inds_array)] 

演示:

>>> x, y, z = np.ogrid[:2,:4,:5] 
>>> M = 100*x + 10*y + z 
>>> M.shape 
(2, 4, 5) 
>>> inds = [(0, 0), (2, 1), (3, 4), (1, 2)] 
>>> inds_array = np.moveaxis(np.array(inds), -1, 0); inds_array 
array([[0, 2, 3, 1], 
       [0, 1, 4, 2]]) 
>>> M[np.index_exp[:] + tuple(inds_array)]  # same as M[:, [0, 2, 3, 1], [0, 1, 4, 2]] 
array([[  0,  21,  34,  12], 
       [100, 121, 134, 112]])