为 numpy 数组的每一行采样唯一的列索引 [英] Sampling unique column indexes for each row of a numpy array

查看:70
本文介绍了为 numpy 数组的每一行采样唯一的列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to generate a fixed number of random column indexes (without replacement) for each row of a numpy array.

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

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

If I fixed the required column number to 2, I want something like

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

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

I am looking for a non-loop Numpy based solution. I tried with choice, but with the replacement=False I get error

ValueError: 不能采用比总体更大的样本'替换=假'

ValueError: Cannot take a larger sample than population when 'replace=False'

推荐答案

这是一种受这篇文章 -

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]])

这篇关于为 numpy 数组的每一行采样唯一的列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆