python - Numpy: Replace random elements in an array -
i googled bit , didn't find answers.
the thing is, have 2d numpy array , i'd replace of values @ random positions.
i found answers using numpy.random.choice create mask array. unfortunately not create view on original array can not replace values.
so here example of i'd do.
imagine have 2d array float values.
[[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]] and i'd replace arbitrary amount of elements. nice if tune parameter how many elements going replaced. possible result this:
[[ 3.234, 2., 3.], [ 4., 5., 6.], [ 7., 8., 2.234]] i couldn't think of nice way accomplish this. appreciated.
edit
thanks quick replies.
just mask input array random 1 of same shape.
import numpy np # input array x = np.array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]]) # random boolean mask values changed mask = np.random.randint(0,2,size=x.shape).astype(np.bool) # random matrix same shape of data r = np.random.rand(*x.shape)*np.max(x) # use mask replace values in input array x[mask] = r[mask] produces this:
[[ 1. 2. 3. ] [ 4. 5. 8.54749399] [ 7.57749917 8. 4.22590641]]
Comments
Post a Comment