dimanche 2 décembre 2018

Random index of a non zero numpy array

I hope this hasn't been asked before. Not sure how I can reformulate the question. This post is quite similar but still not exactly what I'm looking for.

I have a numpy array with a variable length (something between 4-12). The values of the array are either 0 or 1. I'd like to get the index of a random sample from the array, which is not 0.

My idea was to do something like this:

def sample(self):
        flag = 0
        while flag == 0:
            sampleValue = randint(0, len(myArray())-1)
            flag = myArray()[sampleValue]
        return sampleValue

But thats not really good code and will eventually get trapped in a never ending while loop. Of course I could improve this. Chances are high there's a much more beautiful way of doing this in python :)

Aucun commentaire:

Enregistrer un commentaire