How to do weighted random sample of categories in python

后端 未结 9 2138

Given a list of tuples where each tuple consists of a probability and an item I\'d like to sample an item according to its probability. For example, give the list [ (.3, \'a\'),

9条回答
  •  温柔的废话
    2021-01-31 18:21

    This may be of marginal benefit but I did it this way:

    import scipy.stats as sps
    N=1000
    M3 = sps.multinomial.rvs(1, p = [0.3,0.4,0.3], size=N, random_state=None)
    M3a = [ np.where(r==1)[0][0] for r in M3 ] # convert 1-hot encoding to integers
    

    This is similar to @eat's answer.

提交回复
热议问题