Sample each group after pandas groupby

前端 未结 2 569
感动是毒
感动是毒 2020-11-28 11:16

I know this must have been answered some where but I just could not find it.

Problem: Sample each group after groupby operation.



        
2条回答
  •  臣服心动
    2020-11-28 11:47

    pandas >= 1.1: GroupBy.sample

    This works like magic:

    # np.random.seed(0)
    df.groupby('b').sample(frac=.3) 
    
       a  b
    5  6  0
    0  1  1
    

    pandas <= 1.0.X

    You can use GroupBy.apply with sample. You do not need to use a lambda; apply accepts keyword arguments:

    df.groupby('b', group_keys=False).apply(pd.DataFrame.sample, frac=.3)
    
       a  b
    5  6  0
    0  1  1
    

提交回复
热议问题