I want to create a randomized bool array with a given length a given number of True values efficiently in Python. I could not find a single command to do so, the following does what I want (twice). Is there anything more elegant way to do it?
import numpy as np
def randbool(length,numtrue):
index_array=np.random.choice(length,numtrue,replace=False)
bool_array=np.zeros(length,dtype=bool)
bool_array[index_array]=True
return(bool_array)
def randbool2(length,numtrue):
bool_array=np.hstack((np.tile(True,numtrue),np.tile(False,length-numtrue)))
np.random.shuffle(bool_array)
return(bool_array)
print(randbool(5,2))
print(randbool2(5,2))
Aucun commentaire:
Enregistrer un commentaire