且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为 numpy 数组的每一行采样唯一的列索引

更新时间:2022-06-03 18:04:49

这是一种受这篇文章启发的矢量化方法> -

Here's one vectorized approach inspired by this post -

def random_unique_indexes_per_row(A, N=2):
    m,n = A.shape
    return np.random.rand(m,n).argsort(1)[:,:N]

样品运行 -

In [146]: A
Out[146]: 
array([[3, 5, 2, 3, 3],
       [1, 3, 3, 4, 5],
       [3, 5, 4, 2, 1],
       [1, 2, 3, 5, 3]])

In [147]: random_unique_indexes_per_row(A, N=2)
Out[147]: 
array([[4, 0],
       [0, 1],
       [3, 2],
       [2, 0]])
In [148]: random_unique_indexes_per_row(A, N=3)
Out[148]: 
array([[2, 0, 1],
       [3, 4, 2],
       [3, 2, 1],
       [4, 3, 0]])