我有一个非常大的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]]
当前回答
如果你想生成多个随机的行子集,例如,如果你在做RANSAC。
num_pop = 10
num_samples = 2
pop_in_sample = 3
rows_to_sample = np.random.random([num_pop, 5])
random_numbers = np.random.random([num_samples, num_pop])
samples = np.argsort(random_numbers, axis=1)[:, :pop_in_sample]
# will be shape [num_samples, pop_in_sample, 5]
row_subsets = rows_to_sample[samples, :]
其他回答
我很惊讶这个更容易阅读的解决方案在10多年后还没有被提出 :
import random
b = np.array(
random.choices(a, k=2)
)
编辑 :啊,也许是因为它只在Python 3.6中引入,但仍然……
如果你需要相同的行,但只是一个随机样本,
import random
new_array = random.sample(old_array,x)
这里x必须是一个'int'定义你想随机选择的行数。
可以使用随机数生成器从给定数组中生成随机样本:
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之前,我不相信有不需要替换就能生成随机列表的好方法。也许您可以设置一个小定义,以确保这两个值不相同。
这是一个老帖子,但这是最适合我的:
A[np.random.choice(A.shape[0], num_rows_2_sample, replace=False)]
将replace=False更改为True以获得相同的东西,但使用replacement。