這里有一種方法可以獲得您想要的結果,并增加輸出的再現(xiàn)性。我們從輸入(fact)數(shù)組中為兩組中的每一組繪制隨機索引值,無需替換。然后,我們創(chuàng)建一個新的輸出數(shù)組,在其中,我們在與繪制的索引值對應的位置分配1,并在其他任何地方分配0。 import numpy as npfrom numpy.random import RandomStaterng = RandomState(123)fact = np.array( (2,2,2,2,1,2,1,1,2,2,2,1,2,2,2,1,2,2,2,1,2,2,1,1,2,1,2,2,2,2,2,2,1,2,2), dtype='int8')idx_arr = np.hstack( ( rng.choice(np.argwhere(fact == 1).flatten(), 8, replace=False), rng.choice(np.argwhere(fact == 2).flatten(), 20, replace=False), ))out = np.zeros_like(fact, dtype='int8')np.put(out, idx_arr, 1)print(out)# [0 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1]