Reputation: 21961
I have foll. 2D numpy array:
array([[[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
...,
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768],
[-32768, -32768, -32768, ..., -32768, -32768, -32768]]], dtype=int16)
with following unique values:
array([-32768, 401, 402, 403, 404], dtype=int16)
Is there a way I can create a new array where 10% of the cells with 401 are changed to 500? I can use np.random.random_sample()
to start but not how to select specified percentage of cells (e.g. 10% from this numpy 2D array)
Upvotes: 1
Views: 502
Reputation: 19634
Denote your array by a
. Then this will do the job:
locs=np.vstack(np.where(a==401)).T
n=len(locs)
changes_loc=np.random.permutation(locs)[:n//10]
a[changes_loc[:,0],changes_loc[:,1]]=500
Here is a small example (with different numbers and 25% instead of 10%, just to depict the behavior):
a=np.array([[1,2,3],[4,1,5],[1,1,7]])
locs=np.vstack(np.where(a==1)).T
n=len(locs)
changes_loc=np.random.permutation(locs)[:n//4]
a[changes_loc[:,0],changes_loc[:,1]]=70
the result is
array([[70, 2, 3],
[ 4, 1, 5],
[ 1, 1, 7]])
Upvotes: 2