我有一个非常大的2D数组,看起来像这样:
a=
[[a1, b1, c1],
[a2, b2, c2],
...,
[an, bn, cn]]
使用numpy,是否有一种简单的方法来获得一个新的2D数组,例如,从初始数组a中随机抽取2行(没有替换)?
e.g.
b=
[[a4, b4, c4],
[a99, b99, c99]]
我有一个非常大的2D数组,看起来像这样:
a=
[[a1, b1, c1],
[a2, b2, c2],
...,
[an, bn, cn]]
使用numpy,是否有一种简单的方法来获得一个新的2D数组,例如,从初始数组a中随机抽取2行(没有替换)?
e.g.
b=
[[a4, b4, c4],
[a99, b99, c99]]
当前回答
可以使用随机数生成器从给定数组中生成随机样本:
rng = np.random.default_rng()
b = rng.choice(a, 2, replace=False)
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]])
把它放在一起作为一般情况:
A[np.random.randint(A.shape[0], size=2), :]
无替代(numpy 1.7.0+):
A[np.random.choice(A.shape[0], 2, replace=False), :]
在1.7之前,我不相信有不需要替换就能生成随机列表的好方法。也许您可以设置一个小定义,以确保这两个值不相同。
我很惊讶这个更容易阅读的解决方案在10多年后还没有被提出 :
import random
b = np.array(
random.choices(a, k=2)
)
编辑 :啊,也许是因为它只在Python 3.6中引入,但仍然……
我看到有人建议排列。事实上,它可以变成一行:
>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]
array([[0, 3, 0],
[3, 1, 2]])
这与Hezi Rasheff提供的答案类似,但简化了,以便新的python用户能够理解发生了什么(我注意到许多新的数据科学学生以最奇怪的方式获取随机样本,因为他们不知道他们在用python做什么)。
你可以使用以下方法从数组中获取一些随机下标:
indices = np.random.choice(A.shape[0], number_of_samples, replace=False)
然后你可以使用你的numpy数组的花哨索引来获得这些索引的样本:
A[indices]
这将从数据中得到指定数量的随机样本。
这是一个老帖子,但这是最适合我的:
A[np.random.choice(A.shape[0], num_rows_2_sample, replace=False)]
将replace=False更改为True以获得相同的东西,但使用replacement。