vendredi 12 mars 2021

How to extract a random sample from a pandas dataframe with frequencies?

Given 16 balls with a color distribution as following,

In[1]: df = pd.DataFrame([10,5,1],index=['red', 'green','blue'], columns=['balls'])
In[2]: df
Out[2] 
            balls
    red       10
    green      5
    blue       1

I would like to extract a random subset of, say, 10 balls, for instance 7 red, 2 green and 1 blue. I cannot use df.sample(), because that will only give me a color, possibly weighted by 'balls', unless I put it in a loop and extract 1 ball at the time and updating the remaining number of balls. This is extremely slow however, when we have 100.000 balls with 500 colors and we want to randomly extract 80.000 of them. I could make a list,

In[3]: list = ['blue', 'blue', 'blue', ..., 'green', 'green', ..., 'blue']

and take 10 random integers between 0 and len(list), but this seems a bit cumbersome. Is there an easy and fast way to solve this?




Aucun commentaire:

Enregistrer un commentaire