numpy:从2D数组中获取随机的行集 [英] Numpy: Get random set of rows from 2D array

查看:51
本文介绍了numpy:从2D数组中获取随机的行集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的2D数组,看起来像这样:

I have a very large 2D array which looks something like this:

a=
[[a1, b1, c1],
 [a2, b2, c2],
 ...,
 [an, bn, cn]]

使用numpy,是否有一种简单的方法来获取新的2D数组,例如从初始数组a中获得2个随机行(无需替换)?

Using numpy, is there an easy way to get a new 2D array with, e.g., 2 random rows from the initial array a (without replacement)?

例如

b=
[[a4,  b4,  c4],
 [a99, b99, c99]]

推荐答案

>>> A = np.random.randint(5, size=(10,3))
>>> A
array([[1, 3, 0],
       [3, 2, 0],
       [0, 2, 1],
       [1, 1, 4],
       [3, 2, 2],
       [0, 1, 0],
       [1, 3, 1],
       [0, 4, 1],
       [2, 4, 2],
       [3, 3, 1]])
>>> idx = np.random.randint(10, size=2)
>>> idx
array([7, 6])
>>> A[idx,:]
array([[0, 4, 1],
       [1, 3, 1]])

在一般情况下将其放在一起:

Putting it together for a general case:

A[np.random.randint(A.shape[0], size=2), :]

对于非替换(numpy 1.7.0 +):

For non replacement (numpy 1.7.0+):

A[np.random.choice(A.shape[0], 2, replace=False), :]

我不认为有一种很好的方法可以在不替换1.7之前生成随机列表.也许您可以设置一个小的定义,以确保两个值不相同.

I do not believe there is a good way to generate random list without replacement before 1.7. Perhaps you can setup a small definition that ensures the two values are not the same.

这篇关于numpy:从2D数组中获取随机的行集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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