【问题标题】:How to randomly select fixed number of rows (if greater) per group else select all rows in pandas?如何随机选择每组固定数量的行(如果更大),否则选择熊猫中的所有行?
【发布时间】:2020-10-17 03:15:01
【问题描述】:

示例数据框:

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

如何为每个Group_Id 随机选择固定数量的行? This answer 建议使用方法:

df.groupby('Group_Id').apply(lambda x: x.sample(2)).reset_index(drop=True)

但如果任何组的行数少于2,则会引发错误。在这种情况下,我希望能够选择所有行。 .head() 允许这样做,但我想要随机样本而不是初始行。

假设我希望每个Group_Id 最多随机抽取两次,我会得到:

    Name Group_Id
    AAA  1
    BDF  1
    CCC  2
    XYZ  2
    DEF  3

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只有当您有更多行时,您才可以选择采样:

    n = 2
    (df.groupby('Group_Id')
       .apply(lambda x: x.sample(n) if len(x)>n else x  )
       .reset_index(drop=True)
    )
    

    你也可以尝试洗牌整个数据和groupby().head():

    df.sample(frac=1).groupby('Group_Id').head(2)
    

    输出:

      Name  Group_Id
    5  DEF         3
    0  AAA         1
    2  BDF         1
    3  CCC         2
    4  XYZ         2
    

    【讨论】:

      【解决方案2】:

      您可以打乱每个子组并获取前 n 行。它会自动取 n 或实际的最小值。

      n=2
      df2 = df.groupby('Group_Id').apply(lambda x: x.sample(frac=1)[:n]).reset_index(drop=True)
            
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-14
        • 2017-08-21
        • 1970-01-01
        • 2020-12-09
        • 2021-07-21
        • 2018-10-27
        • 2022-07-18
        • 2018-09-11
        相关资源
        最近更新 更多