user308827
user308827

Reputation: 21961

Select specific percentage of cells at random from numpy 2D array

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

Answers (1)

Miriam Farber
Miriam Farber

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

Related Questions