如何找到分位数的索引

时间:2016-07-16 15:30:19

标签: python pandas

我使用熊猫系列,我想找到代表分位数的索引值。

如果我有:

np.random.seed(8)
s = pd.Series(np.random.rand(6), ['a', 'b', 'c', 'd', 'e', 'f'])
s

a    0.873429
b    0.968541
c    0.869195
d    0.530856
e    0.232728
f    0.011399
dtype: float64

并且

s.quantile(.5)

我得到了

0.70002511588475946

我想知道的是s的索引值是什么,它代表分位数值之前的点。在这种情况下,我知道索引值应为d

2 个答案:

答案 0 :(得分:3)

如果将interpolation参数设置为'lower''higher''nearest',则可以通过以下方式更简单地解决问题:

s[s == s.quantile(.5, interpolation='lower')]

我猜想这种方法比piRSquared的解决方案还快一点

答案 1 :(得分:2)

使用sort_values,颠倒顺序,查找小于或等于计算的分位数的所有内容,然后找到idxmax

(s.sort_values()[::-1] <= s.quantile(.5)).idxmax()

或者:

(s.sort_values(ascending=False) <= s.quantile(.5)).idxmax()

我们可以将其功能化:

def idxquantile(s, q=0.5, *args, **kwargs):
    qv = s.quantile(q, *args, **kwargs)
    return (s.sort_values()[::-1] <= qv).idxmax()

idxquantile(s)