I have a numpy array as follows.
data = np.array([True, True, True, True, False, True, True, False, True, True, False])
From the locations of 'True', I have to randomly sample 3 locations and keep them as True, besides them, convert as False.
I tried as:
indx = np.random.choice(len(data),3,replace=False)
data[~indx] = False
How to do it in a better (1. easy, 2. performance, 3. elegance)?
print (data)
Also, how to sample only from 'True` locations? My code is doing from all locations and incorrect.
For elegance, here's one -
n = 3
idx = np.flatnonzero(data)
r = np.random.choice(idx, n, replace=False)
data[idx[~np.isin(idx,r)]] = False
For performance -
s = data.sum()
t_mask = np.zeros(s, dtype=bool)
t_mask[np.random.choice(s, n, replace=False)] = True
data[data] = t_mask
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.