 pyigal - 2 years ago 206
Python Question

# Choose random elements from specific elements of an array

I have a 1D (numpy) array with boolean values. for example:

``````x = [True, True, False, False, False, True, False, True, True, True, False, True, True, False]
``````

The array contains 8 True values. I would like to choose, for example, 3 (must be less than 8 in this case) random elements out of the 8 that exist and get as an output an array with the same length as x with Trues at 3 random places.
A possible result can be:

``````x = [True, True, False, False, False, False, False, False, False, False, False, False, True, False]
``````

How to implement it? Divakar

One approach would be -

``````# Get the indices of True values
idx = np.flatnonzero(x)

# Get unique indices of length 3 less than the number of indices and
# set those in x as False
x[np.random.choice(idx, len(idx)-3, replace=0)] = 0
``````

Sample run -

``````# Input array
In : x
Out:
array([ True,  True, False, False, False,  True, False,  True,  True,
True, False,  True,  True, False], dtype=bool)

# Get indices
In : idx = np.flatnonzero(x)

# Set 3 minus number of True indices as False
In : x[np.random.choice(idx, len(idx)-3, replace=0)] = 0

# Verify output to have exactly three True values
In : x
Out:
array([ True, False, False, False, False, False, False,  True, False,
False, False,  True, False, False], dtype=bool)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download