Python: Random selection per group

后端 未结 9 901
面向向阳花
面向向阳花 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:56

    The solutions offered fail if a group has fewer samples than the desired sample size n. This addresses this problem:

    n = 10
    df.groupby('Group_Id').apply(lambda x: x.sample(min(n,len(x)))).reset_index(drop=True)
    

提交回复
热议问题