I already googled a bit and didn't find any good answers.
The thing is, I have a 2d numpy array and I'd like to replace some of its values at random positions.
I found some answers using numpy.random.choice to create a mask for the array. Unfortunately this does not create a view on the original array so I can not replace its values.
So here is an example of what I'd like to do.
Imagine I have 2d array with float values.
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]]
And then I'd like to replace an arbitrary amount of elements. It would be nice if I could tune with a parameter how many elements are going to be replaced. A possible result could look like this:
[[ 3.234, 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 2.234]]
I couldn't think of nice way to accomplish this. Help is appreciated.
EDIT
Thanks for all the quick replies.
It's easy to choose indices at random when the array is one-dimensional, so I'd recommend reshaping the array to 1D, changing random elements, then reshaping back to the original shape.
For example:
So this does something like:
Here I've replaced elements choosing from a normal distribution --- but obviously you can replace the call to
np.random.normal
with whatever you want.You could always randomly generated
n
integers to index a flattened view (1D version) of your array, and set those indexed values equal ton
random values:You could scale the randomly generated values by some factor if you want values greater than 1; for example
np.random.rand(n) * m
would yield values between 0 andnp.product(x.shape)
.Note that
numpy.ravel
operates inplace by default.Just mask your input array with a random one of the same shape.
Produces something like this:
You can create bernoulli random variables using scipy, and the parameter p will control what percent of values in your array you end up replacing. Then replace values in your original array based on whether the bernoulli random variable takes on a value of 0 or 1.
Not really optimized, but a starting point to help you figuring out a way of doing it: