假设数据总是排序的(感谢@juanpa.arrivillaga),您可以使用rank
PandasSeries
类中的方法。rank()
需要几个参数。其中之一是pct
:
pct : 布尔值,默认为 False
计算数据的百分比排名
计算百分比排名有不同的方法。这些方法由参数控制method
:
方法:{'average', 'min', 'max', 'first', 'dense'}
你需要的方法"max"
:
max:组中的最高排名
让我们看一下rank()
带有这些参数的方法的输出:
import numpy as np
import pandas as pd
series = [1,2,2,2,2,2,2,2,2,2,2,5,5,6,7,8]
S = pd.Series(series)
percentage_rank = S.rank(method="max", pct=True)
print(percentage_rank)
这基本上为您提供了以下每个条目的百分位数Series
:
0 0.0625
1 0.6875
2 0.6875
3 0.6875
4 0.6875
5 0.6875
6 0.6875
7 0.6875
8 0.6875
9 0.6875
10 0.6875
11 0.8125
12 0.8125
13 0.8750
14 0.9375
15 1.0000
dtype: float64
为了检索三个百分位数的索引,您在 中查找与Series
您感兴趣的百分位数具有相等或更高百分比排名的第一个元素。该元素的索引是您需要的索引。
index25 = S.index[percentage_rank >= 0.25][0]
index50 = S.index[percentage_rank >= 0.50][0]
index75 = S.index[percentage_rank >= 0.75][0]
print("25 percentile: index {}, value {}".format(index25, S[index25]))
print("50 percentile: index {}, value {}".format(index50, S[index50]))
print("75 percentile: index {}, value {}".format(index75, S[index75]))
这为您提供了输出:
25 percentile: index 1, value 2
50 percentile: index 1, value 2
75 percentile: index 11, value 5