lundi 12 avril 2021

Get indices from one randomly chosen true element in a boolean array

I have a boolean array from which I would like the indices of one randomly chosen element that equals True. The output should be a tuple with the (x,y,z) indices of that element.

Is there a more elegant and/or efficient way to do this instead of doing the following?

import numpy as np
rng = np.random.RandomState(42)

# create a random 3D boolean array
m = rng.choice(a=[False, True],size=(3,3,3))

# get (x,y,z) from one random cell in the boolean array which equals True
indices_where_true = np.where(m)
random_int = rng.randint(len(indices_where_true[0]),size=1)
random_index = (indices_where_true[0][random_int][0],
                indices_where_true[1][random_int][0],
                indices_where_true[2][random_int][0])



Aucun commentaire:

Enregistrer un commentaire