pyigal pyigal - 10 months ago 88
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?

Answer Source

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 [79]: x
Out[79]: 
array([ True,  True, False, False, False,  True, False,  True,  True,
        True, False,  True,  True, False], dtype=bool)

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

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

# Verify output to have exactly three True values
In [82]: x
Out[82]: 
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