我有一个非常大的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]]
当前回答
另一种选择是创建一个随机掩码,如果您只是想按某个因素对数据进行抽样。假设我想降低样本到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%的行,随机采样。
其他回答
如果你需要相同的行,但只是一个随机样本,
import random
new_array = random.sample(old_array,x)
这里x必须是一个'int'定义你想随机选择的行数。
另一种选择是创建一个随机掩码,如果您只是想按某个因素对数据进行抽样。假设我想降低样本到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%的行,随机采样。
如果你想生成多个随机的行子集,例如,如果你在做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, :]
我看到有人建议排列。事实上,它可以变成一行:
>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]
array([[0, 3, 0],
[3, 1, 2]])
我很惊讶这个更容易阅读的解决方案在10多年后还没有被提出 :
import random
b = np.array(
random.choices(a, k=2)
)
编辑 :啊,也许是因为它只在Python 3.6中引入,但仍然……