Вот один способ, основанный на np.random.choice
-
def add_random_n_places(a, n):
# Generate a float version
out = a.astype(float)
# Generate unique flattened indices along the size of a
idx = np.random.choice(a.size, n, replace=False)
# Assign into those places ramdom numbers in [-1,1)
out.flat[idx] += np.random.uniform(low=-1, high=1, size=n)
return out
Образцы прогонов -
In [89]: a # input array
Out[89]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [90]: add_random_n_places(a, 2)
Out[90]:
array([[0. , 1. , 2. ],
[2.51523009, 4. , 5. ],
[6. , 7. , 8.36619255]])
In [91]: add_random_n_places(a, 4)
Out[91]:
array([[0.67792859, 0.84012682, 2. ],
[3. , 3.71209157, 5. ],
[6. , 6.46088001, 8. ]])