Skip to main content
 首页 » 编程设计

python之如何在没有 python 循环的情况下进行这种类型的 2D "fancy"索引

2024年10月25日12虾米哥

给定一个要采样的二维数组和一个二维索引数组(索引数组的轴 1 与源轴和目标轴 1 对齐,索引数组的轴 0 与目标轴 0 对齐并包含索引源数组)如何在不迭代两个轴之一的情况下生成目标数组?

想要在没有 python 迭代的情况下复制这个结果:

wid = 10 
hig = 5 
ix_ct = 2 
 
src = np.arange(wid*hig, dtype=float).reshape((hig, wid)) 
dst = np.empty((ix_ct, wid), dtype=float) 
ix = np.random.random_integers(0, hig-1, (ix_ct, wid)) 
 
for i in range(ix.shape[1]): 
    j = ix[:,i] 
    dst[:,i] = src[j,i] 

请您参考如下方法:

所有你需要的是给 src 一个匹配(广播方面)ix 的第二个索引数组:

src[ix,np.arange(ix.shape[1])] 

例如

array([[ 40.,  31.,  42.,  23.,  34.,  25.,   6.,  37.,  18.,   9.], 
   [ 40.,  21.,  12.,  43.,   4.,  25.,  46.,  17.,  38.,  29.]]) 

为了解释,考虑一个二维索引数组,iy,与 ix 形状相同,但具有迭代中的 i 值:

In [72]: iy=np.array([np.arange(10),np.arange(10)]) 
In [75]: iy 
Out[75]:  
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) 
In [76]: src[ix,iy] 
Out[76]:  
array([[ 40.,  31.,  42.,  23.,  34.,  25.,   6.,  37.,  18.,   9.], 
       [ 40.,  21.,  12.,  43.,   4.,  25.,  46.,  17.,  38.,  29.]]) 

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing 整数数组“高级”索引的文档