Pandas:计算子组内的百分位数?

2024-09-30 01:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Pandas数据帧,看起来像这样:

 school_id  uni_id  points
 123        44      180
 123        45      160
 123        45      160
 123        48      110
 124        44      180
 124        45      160
 124        47      130
 123        48      120

生成如下,以帮助善意的回答者:

^{pr2}$

我想添加一个percentile列,它表示每个学校的points值的百分位数。所以这个数据集应该是这样的:

 school_id  uni_id  points  percentile
 123        44      180     100
 123        45      160     50
 123        45      160     50
 123        48      110     0
 124        44      180     100
 124        45      160     66
 124        47      130     33
 123        48      120     0

最好的办法是什么?我假设我需要按school_id分组,然后以某种方式在每个子组中执行df.quantile(),然后解组?在

更新:也许我需要从这样的开始。。。df.groupby('school_id')['points'].rank(ascending=False)然后将秩除以每组的长度,使其在0到100之间正规化?在


Tags: 数据idpandasdf方式学校pointsuni
2条回答

在计算按"school_id"分组的子组之间的数值数据秩时,可以将pct=True指定为^{}方法的附加参数:

df.assign(percentile=df.groupby("school_id")['points'].rank(pct=True).mul(100))

enter image description here

检查(针对一个实例):

^{pr2}$

你想在这里做几件事。在

  • 你想让你的排名更高
  • 你希望最低值为0,最高值为100。我称之为包容性排名

我创建了一个单独的函数来应用。在

def dense_inclusive_pct(x):
    # I subtract one to handle the inclusive bit
    r = x.rank(method='dense') - 1
    return r / r.max() * 100

df.assign(pct=df.groupby('school_id').points.apply(dense_inclusive_pct).astype(int))

   points  school_id  uni_id  pct
0     180        123      44  100
1     160        123      45   50
2     160        123      45   50
3     110        123      48    0
4     180        124      44  100
5     160        124      45   66
6     130        124      47   33
7     120        124      48    0

相关问题 更多 >

    热门问题