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

时间:2018-07-11 07:20:29

标签: python python-2.7 numpy random

我想为numpy数组的每一行生成固定数量的随机列索引(不替换)。

A = np.array([[3, 5, 2, 3, 3],
       [1, 3, 3, 4, 5],
       [3, 5, 4, 2, 1],
       [1, 2, 3, 5, 3]])

如果我将所需的列号固定为2,我想要类似的东西

np.array([[1,3],
          [0,4],
          [1,4],
          [2,3]])

我正在寻找基于Numpy的非循环解决方案。我尝试了选择,但是用replace = False却得到了错误

  

ValueError:在以下情况下无法获取比总体更大的样本:   'replace = False'

3 个答案:

答案 0 :(得分:1)

喜欢吗?

B = np.random.randint(5, size=(len(A), 2))

答案 1 :(得分:1)

这是一种受this post启发的矢量化方法-

Image image = ImageIO.read(getClass().getResource("images/icon-tender-check-press.png"));
    button.setIcon(new ImageIcon(image));

样品运行-

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

答案 2 :(得分:0)

您可以按以下方式使用random.choice()

def random_indices(arr, n):
    x, y = arr.shape
    return np.random.choice(np.arange(y), (x, n))
    # or return np.random.randint(low=0, high=y, size=(x, n))

演示:

In [34]: x, y = A.shape

In [35]: np.random.choice(np.arange(y), (x, 2))
Out[35]: 
array([[0, 2],
       [0, 1],
       [0, 1],
       [3, 1]])

作为一种实验方法,这里的方法是在99%的时间内给出唯一索引:

In [60]: def random_ind(arr, n):
    ...:     x, y = arr.shape
    ...:     ind = np.random.randint(low=0, high=y, size=(x * 2, n))
    ...:     _, index = np.unique(ind.dot(np.random.rand(ind.shape[1])), return_index=True)
    ...:     return ind[index][:4]
    ...: 
    ...: 
    ...: 

In [61]: random_ind(A, 2)
Out[61]: 
array([[0, 1],
       [1, 0],
       [1, 1],
       [1, 4]])

In [62]: random_ind(A, 2)
Out[62]: 
array([[1, 0],
       [2, 0],
       [2, 1],
       [3, 1]])

In [64]: random_ind(A, 3)
Out[64]: 
array([[0, 0, 0],
       [1, 1, 2],
       [0, 4, 1],
       [2, 3, 1]])

In [65]: random_ind(A, 4)
Out[65]: 
array([[0, 4, 0, 3],
       [1, 0, 1, 4],
       [0, 4, 1, 2],
       [3, 0, 1, 0]])

如果没有4个唯一项,则此函数将在IndexError行返回return ind[index][:4],在这种情况下,您可以重复该函数以确保获得所需的结果。