Arrays 在numpy数组中随机排列索引子集(类似于非黑色像素)的最快方法

Arrays 在numpy数组中随机排列索引子集(类似于非黑色像素)的最快方法,arrays,python-3.x,numpy,permutation,Arrays,Python 3.x,Numpy,Permutation,我有一个形状的3D numpy数组,例如:(500500,3),只有一些[I,j,:]单元格在所有3个通道中为零(想象一个RGB图像,所有通道为零=黑色像素)。执行这些值的就地排列的最快方法是什么,以使“全部零”[i,j]单元在排列后保持不变(在图像示例中,黑色像素保持黑色,其余所有像素保持排列) 下面是这样一个阵列的示例,以及一个可行的解决方案(但我希望它尽可能快): 任何更快的解决方案都将不胜感激 这是一个完全矢量化的解决方案,基于: a_perm=np.zero_like(a) 行,列=n

我有一个形状的3D numpy数组,例如:(500500,3),只有一些[I,j,:]单元格在所有3个通道中为零(想象一个RGB图像,所有通道为零=黑色像素)。执行这些值的就地排列的最快方法是什么,以使“全部零”[i,j]单元在排列后保持不变(在图像示例中,黑色像素保持黑色,其余所有像素保持排列)

下面是这样一个阵列的示例,以及一个可行的解决方案(但我希望它尽可能快):


任何更快的解决方案都将不胜感激

这是一个完全矢量化的解决方案,基于:

a_perm=np.zero_like(a)
行,列=np,其中(a.any(轴=-1))
排列=np.随机排列(列(行))
a_perm[rows[perm],cols[perm]]=a[rows,cols]

几乎-由于某种原因,a_perm[100:200,100:200]中有零(它应该只有[1,1,1]或[2,2,2]的混合)。对不起,我误解了你的问题。我编辑的答案应该很好。
# make the numpy array
a = np.zeros((500,500,3))
a[100:200,100:200] = 1
a[200:300,200:300] = 2

# extract (i,j) indices and corresponding RGB values for indices that are not all zero RGB
idx_to_val = {idx[:-1]: a[idx[:-1]] for idx, _ in np.ndenumerate(a) if sum(a[idx[:-1]]) > 0}
idx, vals = list(idx_to_val.keys()), list(idx_to_val.values())

# shuffle the (i,j) indices
np.random.shuffle(idx)

# fill in a new numpy array at these not-all-zero indices with the non-shuffled values 
a_perm = np.zeros(a.shape)
a_perm[tuple(zip(*idx))] = vals