如何以 p 的概率交换数组中的元素?

How to swap elements in a array with a probability of p?

假设我有一个 numpy 数组 a = np.random.randint(0,20,10) 我想以 p 的概率排列它的元素,即如果 p = 0.2 每个元素有 20% 的概率交换位置另一个元素。我知道 numpy.random.permutate() 函数,但这只允许排列数组中的所有元素。这可以在 python 中有效地完成吗?

诀窍是首先选择哪些元素将成为参与排列的候选元素。

import numpy as np

a = np.random.randint(0,20,10) # original array
p = 0.2

ix = np.arange(a.size)  # indexes of a
will_swap = np.random.random(a.size) <= p  # draw which elements will be candidates for swapping
after_swap = np.random.permutation(ix[will_swap]) # permute the canidadates
ix[will_swap] = after_swap # update ix with the swapped candidates
a = a[ix]
print(a) # --> [0 1 8 3 4 5 6 7 2 9]