Issue
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.
Solution
Just mask your input array with a random one of the same shape.
import numpy as np
# input array
x = np.array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]])
# random boolean mask for which values will be changed
mask = np.random.randint(0,2,size=x.shape).astype(np.bool)
# random matrix the same shape of your data
r = np.random.rand(*x.shape)*np.max(x)
# use your mask to replace values in your input array
x[mask] = r[mask]
Produces something like this:
[[ 1. 2. 3. ]
[ 4. 5. 8.54749399]
[ 7.57749917 8. 4.22590641]]
Answered By - derricw
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.