【问题标题】:Pandas groupby where the column value is greater than the group's x percentilePandas groupby,其中列值大于组的 x 百分位数
【发布时间】:2019-02-24 02:12:34
【问题描述】:

我有一个熊猫数据框如下:

df = pd.DataFrame()
df['Name'] = ['Abby', 'Abby', 'Abby', 'Abby', 'Abby', 'Daniel', 'Daniel', 'Daniel', 'Daniel', 'Daniel']
df['Marks'] = [100, 90, 76, 50, 10, 50, 45, 38, 25, 5]

我想:

  1. 找出每组的第 40 个百分位
  2. 过滤数据框,以便显示该组第 40 个百分位以上的所有值。

因此,我使用以下方法找到了每个组的第 40 个百分位数:

df.groupby('Name').quantile(0.4)

目标是:

我的主要问题是每个组的值没有标准化,因此我无法为整个数据集应用整体百分位值。

但是我看到的关于过滤具有特定值的数据框的所有帮助并没有针对每个组单独执行。我看到了以下问题:

Pandas, groupby where column value is greater than x

Pandas Groupby apply function to count values greater than zero

我的问题基本上建立在以下问题的变体之上: Calculate Arbitrary Percentile on Pandas GroupBy

有没有办法在 Pandas 中做到这一点?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    将您的代码用于百分位数,locge 用于>=(或gt,用于>)和索引匹配:

    df = df.set_index('Name')
    df.loc[df.Marks.ge(df.groupby('Name').quantile(0.4).Marks)]
    
        Name    Marks
    0   Abby    100
    1   Abby    90
    2   Abby    76
    5   Daniel  50
    6   Daniel  45
    7   Daniel  38
    

    【讨论】:

      【解决方案2】:

      您可以使用transform

      df[df.Marks>df.groupby('Name').Marks.transform('quantile',0.4)]
      Out[712]: 
           Name  Marks
      0    Abby    100
      1    Abby     90
      2    Abby     76
      5  Daniel     50
      6  Daniel     45
      7  Daniel     38
      

      【讨论】:

      • 是否可以将这种方法用于扩展分位数而不是全样本分位数?
      • 我想出了相同的解决方案,只晚了 4 分钟:)
      • @Yuca 你的意思是消费分位数?我想我们可以在这里使用 lambda
      • 我相信你知道 pandas 的滚动和扩展。扩展分位数将是每行可用的分位数。我只是好奇,因为我用 numba 和 assign 来做到这一点
      • @Yuca df.groupby('Name').Marks.expanding().quantile(0.5)
      猜你喜欢
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 2017-01-07
      • 2023-03-13
      • 2014-08-30
      • 2019-08-05
      相关资源
      最近更新 更多