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

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

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

e.g.

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

当前回答

这是一个老帖子,但这是最适合我的:

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

将replace=False更改为True以获得相同的东西,但使用replacement。

其他回答

另一种选择是创建一个随机掩码,如果您只是想按某个因素对数据进行抽样。假设我想降低样本到25%的原始数据集,它目前保存在数组data_arr中:

# generate random boolean mask the length of data
# use p 0.75 for False and 0.25 for True
mask = numpy.random.choice([False, True], len(data_arr), p=[0.75, 0.25])

现在您可以调用data_arr[mask]并返回~25%的行,随机采样。

>>> 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之前,我不相信有不需要替换就能生成随机列表的好方法。也许您可以设置一个小定义,以确保这两个值不相同。

我看到有人建议排列。事实上,它可以变成一行:

>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]

array([[0, 3, 0],
       [3, 1, 2]])

这是一个老帖子,但这是最适合我的:

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

将replace=False更改为True以获得相同的东西,但使用replacement。

这与Hezi Rasheff提供的答案类似,但简化了,以便新的python用户能够理解发生了什么(我注意到许多新的数据科学学生以最奇怪的方式获取随机样本,因为他们不知道他们在用python做什么)。

你可以使用以下方法从数组中获取一些随机下标:

indices = np.random.choice(A.shape[0], number_of_samples, replace=False)

然后你可以使用你的numpy数组的花哨索引来获得这些索引的样本:

A[indices]

这将从数据中得到指定数量的随机样本。