Skip to main content
 首页 » 编程设计

python之numpy 取很多样本而不按行替换

2025年05月04日21luoye11

我有一个很大的 list 。想象一下它看起来像这样:

test = ['llama', 'cow', 'horse', 'fish', 'sheep', 'goat', 'cat', 'dog'] 

我想多次从这个列表中抽样。我希望每个样本都被采集而无需更换。在这种情况下,我想避免 for 循环。

我在 StackOverflow 上看到许多接近的解决方案,但不完全是我在这里需要的。假设我想要的每个样本都是 3 号的。如果我想用替换样本进行抽样,这会起作用:

np.random.choice(test, size=(100, 3)) 

这将给我 100 行,每行 3 个样本。问题是任何特定的行都可能有重复,我不能要求它在没有替换的情况下进行采样,因为 300 > len(test)。

有没有办法保持随机性?我看到了使用 np.argsort 的潜在解决方案,但考虑到正在进行排序,我不确定它们实际上是否仍然是随机的。

请您参考如下方法:

您可以为此使用 random.sample,来自 documentation :

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

然后使用列表理解重复该过程 n_times:

n_times = 100 
n_sample = 3 
[random.sample(test, n_sample) for i in range(n_times)] 
 
[['llama', 'goat', 'sheep'], 
 ['cat', 'horse', 'dog'], 
 ['sheep', 'dog', 'goat'], 
 ['cat', 'cow', 'llama'], 
 ['dog', 'fish', 'horse'], 
 ['llama', 'horse', 'cow'], 
 ['dog', 'goat', 'cow'], 
 ['llama', 'cow', 'sheep'], 
 ['fish', 'dog', 'horse'], 
 ...