Numpy 如何从列索引矩阵设置矩阵单元格

Numpy 如何从列索引矩阵设置矩阵单元格,numpy,Numpy,我想从位置列表和内核中心列表构建一个内核。内核应该是距离每个位置最近的两个中心的指示器 > x = np.array([0.1, .49, 1.9, ]).reshape((3,1)) # Positions > c = np.array([-2., 0.1, 0.2, 0.4, 0.5, 2.]) # centers print x print c [[ 0.1 ] [ 0.49] [ 1.9 ]] [-2. 0.1 0.2 0.4 0.5 2. ]

我想从位置列表和内核中心列表构建一个内核。内核应该是距离每个位置最近的两个中心的指示器

> x = np.array([0.1, .49, 1.9, ]).reshape((3,1))  # Positions
> c = np.array([-2., 0.1,  0.2,  0.4,  0.5,  2.]) # centers
print x
print c

[[ 0.1 ]
 [ 0.49]
 [ 1.9 ]]
[-2.   0.1  0.2  0.4  0.5  2. ]
我想说的是:

array([[ 0, 1, 1, 0, 0, 0],  # Index 1,2 closest to 0.1
       [ 0, 0, 0, 1, 1, 0],  # Index 3,4 closest to 0.49
       [ 0, 0, 0, 0, 1, 1]])  # Index 4,5 closest to  1.9
我可以得到:

> dist = np.abs(x-c)
array([[ 2.1 ,  0.  ,  0.1 ,  0.3 ,  0.4 ,  1.9 ],
       [ 2.49,  0.39,  0.29,  0.09,  0.01,  1.51],
       [ 3.9 ,  1.8 ,  1.7 ,  1.5 ,  1.4 ,  0.1 ]])
以及:

这里我有一个列索引矩阵,但我看不到如何使用它们在另一个矩阵中设置这些列的值(使用有效的numpy操作)


一种方法是初始化零数组,然后使用-

或者,我们可以使用尺寸扩展,并提出一个单一的衬里-

out = (idx[...,None] == np.arange(dist.shape[1])).any(1).astype(int)
对于性能,我建议使用

idx = np.argpartition(dist, 2, axis=1)[:,:2]

超级的!我发现第一种方法比第二种方法快2倍。
out = np.zeros(dist.shape,dtype=int)
out[np.arange(idx.shape[0])[:,None],idx] = 1
out = (idx[...,None] == np.arange(dist.shape[1])).any(1).astype(int)
idx = np.argpartition(dist, 2, axis=1)[:,:2]