Python: Random selection per group

后端 未结 9 902
面向向阳花
面向向阳花 2020-12-01 05:08

Say that I have a dataframe that looks like:

Name Group_Id
AAA  1
ABC  1
CCC  2
XYZ  2
DEF  3 
YYH  3

How could I randomly select one (or m

9条回答
  •  情话喂你
    2020-12-01 05:54

    Using random.choice, you can do something like this:

    import random
    name_group = {'AAA': 1, 'ABC':1, 'CCC':2, 'XYZ':2, 'DEF':3, 'YYH':3}
    
    names = [name for name in name_group.iterkeys()] #create a list out of the keys in the name_group dict
    
    first_name = random.choice(names)
    first_group = name_group[first_name]
    print first_name, first_group
    

    random.choice(seq)

    Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
    

提交回复
热议问题