我需要从 1D NumPy 数组中抽取随机样本而不进行替换。然而,性能至关重要,因为此操作将重复多次。
这是我当前使用的代码:
import numpy as np
# Example array
array = np.array([10, 20, 30, 40, 50])
# Number of samples to draw
num_samples = 3
# Draw samples without replacement
samples = np.random.choice(array, size=num_samples, replace=False)
print("Samples:", samples)
虽然这适用于一个样本,但它需要一个循环来生成多个样本,我相信可能有一种方法可以优化或矢量化此操作,以提高多次采样时的性能。
The sample() is an inbuilt method of the random module which takes the sequence and number of selections as arguments and returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set.
# importing the required module
import random
# list of items
List = [10, 20, 30, 40, 50, 40,
30, 20, 10]
# using the sample() method
UpdatedList = random.sample(List, 3)
# displaying random selections from
# the list without repetition
print(List)