您可以将数组转换为索引,对索引进行采样并转换回值,如下所示:
import numpy as np
np.random.seed(0)
a = np.array([1,2,2,0,3,5])
# Generate an array of indices, values in "a"
# define the number of occurences of their index
a_idx = np.array([i for i in range(len(a))])
a_idx = np.repeat(np.arange(len(a)), a)
# [0, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 5, 5]
# Randomly shuffle indices and pick the n-first
a_sub_idx = np.random.permutation(a_idx)[:target]
# [4, 1, 2, 2, 5]
# Count the number of occurences of each index
a_sub_idx, a_sub_vals = np.unique(a_sub_idx, return_counts=True)
# Generate a new array of values the sampled indices
a_sub = np.zeros(a.shape)
a_sub[a_sub_idx] = a_sub_vals
# [0., 1., 2., 0., 1., 1.]