我不太明白如何编写函数来完成分组的百分位数。我在一个数据框中拥有 1985-2012 年的所有团队;前 10 个如下所示:目前按年份排序。我正在寻找按 Year
分组的 LgRnk
的百分位数。因此,例如,1985 年的 23 LgRank(最差球队)将是 100 个百分点,而 1985 年的 1 LgRank(最佳球队)将是 1 个百分点。 30 2010 年的 LgRank(最差球队)将是 100 个百分位数,等等。它需要按 LgRnk
的不同数量的 b/c 年进行分组。
Team WLPer Year LgRnk W L
19 Sacramento Kings 0.378 1985 18 31 51
0 Atlanta Hawks 0.415 1985 17 34 48
17 Phoenix Suns 0.439 1985 16 36 46
4 Cleveland Cavaliers 0.439 1985 15 36 46
13 Milwaukee Bucks 0.720 1985 3 59 23
3 Chicago Bulls 0.463 1985 14 38 44
16 Philadelphia 76ers 0.707 1985 4 58 24
22 Washington Wizards 0.488 1985 13 40 42
20 San Antonio Spurs 0.500 1985 12 41 41
21 Utah Jazz 0.500 1985 11 41 41
我尝试使用以下方法创建一个函数:scipy.stats.percentileofscore
我不太明白。
最佳答案
您可以在 LgRnk 列上应用:
# just for me to normalize this, so my numbers will go from 0 to 1 in this example
In [11]: df['LgRnk'] = g.LgRnk.rank()
In [12]: g = df.groupby('Year')
In [13]: g.LgRnk.apply(lambda x: x / len(x))
Out[13]:
19 1.0
0 0.9
17 0.8
4 0.7
13 0.1
3 0.6
16 0.2
22 0.5
20 0.4
21 0.3
Name: 1985, dtype: float64
Series groupby 排名(仅适用于 Series.rank
)采用 pct 参数来执行此操作:
In [21]: g.LgRnk.rank(pct=True)
Out[21]:
19 1.0
0 0.9
17 0.8
4 0.7
13 0.1
3 0.6
16 0.2
22 0.5
20 0.4
21 0.3
Name: 1985, dtype: float64
并直接在 WLPer
列上(尽管由于平局而略有不同):
In [22]: g.WLPer.rank(pct=True, ascending=False)
Out[22]:
19 1.00
0 0.90
17 0.75
4 0.75
13 0.10
3 0.60
16 0.20
22 0.50
20 0.35
21 0.35
Name: 1985, dtype: float64
注意:我已经更改了第一行的数字,因此您会在完整 帧中得到不同的分数。
关于python - Pandas 的百分位排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339758/