我有一个中等大的
np
数组(但将来可能会变得更大):
import numpy as np
x = np.arange(100_000).reshape((10_000,10))
我需要迭代地选择一个随机样本(行),确保我不会两次选择相同的样本。目前我正在做
rng = np.random.default_rng(seed=42)
indices = list(range(len(x)))
for _ in range(1000):
i = rng.choice(indices)
## do something with x[i]
indices.remove(i)
但是,我读到
remove
非常慢。有没有更好的方法来跟踪我已经使用的索引?
一种选择可能是将指针(索引)列表保留到数组中,最初按顺序排列,您不需要按任何特定顺序进行采样,并且可以有效地交换和弹出:
rng = np.random.default_rng(seed=42)
indices = np.arange(len(x))
for _ in range(1000):
i = rng.integers(len(indices))
## do something with x[indices[i]]
indices[i] = indices[-1] # swap
del indices[-1] # pop