Luca
Luca

Reputation: 10996

numpy randomly sample from array where the values are not 0

I am creating a numpy binary array with zeros and ones as follows:

import numpy as np
x = np.zeros((10, 10, 10))
x[:4, :4, :4] = 1
x = x.ravel()
np.random.shuffle(x)
x.reshape(10, 10, 10)

Now what I want to do is randomly sample 20 positions within this array where the value is 1. i.e. I want to randomly sample twenty 3D coordinates where the volume elements are turned on.

I am guessing the way to do this would be to get a position mask of all the positions with the positive value and then sample from that but I cannot figure out how to generate that mask with numpy!

Upvotes: 2

Views: 479

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can get the coordinates with np.where. This will give you a 3-tuple with arrays for the indices where the position is 1.

We can use np.transpose(..) or zip(..) to generate 3-tuples with these, and then use for example random.sample(..) to select 20 of these positions.

For example:

>>> random.sample(list(zip(*np.where(x.reshape(10,10,10)))), 20)
[(9, 0, 5), (2, 2, 9), (3, 7, 8), (8, 2, 4), (2, 5, 9), (8, 5, 4), (3, 3, 7), (2, 6, 7), (9, 4, 8), (7, 5, 7), (7, 8, 7), (0, 8, 6), (9, 4, 3), (5, 0, 2), (4, 4, 1), (9, 0, 6), (1, 1, 8), (1, 3, 8), (5, 4, 5), (5, 2, 0)]

Upvotes: 4

Related Questions