我有一个多维ndarray,我希望随机选择1000个要替换的数组。在我看来,这很简单,但是我努力将其与替换部件合并在一起。
此ndarray中有3065个数组。
np.shape(train_spam)
(3065L, 58L)
我尝试使用np.random.shuffle(),但这没有考虑with的替换。
np.random.shuffle(train_spam)
X_train = train_spam[:1000,1:57]
我的最终输出将具有(1000L,58L)的形状。
我想我可以使用ndarray运行循环
X_train = train_spam[0:57]
然后追加,但是我不知道如何正确追加,所以看起来一样。任何帮助将不胜感激
selected = train_spam[np.random.randint(train_spam.shape[0], size=1000)]
k = 1000 # Number of elements to select.
n = train_spam.shape[0] # Number of elements in array.
indices = [random.randrange(n) for i in range(k)] # A plain Python list.
selected = train_spam[np.array(indices)] # Convert indices to ndarray.
如果您有一个普通的Python列表,要从中选择要替换的元素,则可以执行此操作:
pets = ['ant', 'bear', 'cat', 'dog', 'elephant', 'flamingo', 'gorilla', 'horse']
n = len(pets)
k = 10
selected = [pets[random.randrange(n)] for i in range(k)]
a = np.array([[1,2,3],[2,3,4], [5,6,7]])
rng = np.random.default_rng()
rng.choice(a, 2)