如何找到分位数的索引

Bri*_*ian 5 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
Run Code Online (Sandbox Code Playgroud)

并且做

s.quantile(.5)
Run Code Online (Sandbox Code Playgroud)

我得到

0.70002511588475946
Run Code Online (Sandbox Code Playgroud)

我想知道的是s代表该分位数值之前的点的索引值是多少。在这种情况下,我知道索引值应该是d.

piR*_*red 5

使用sort_values,倒序,找到所有小于或等于计算出的分位数,然后找到idxmax

(s.sort_values()[::-1] <= s.quantile(.5)).idxmax()
Run Code Online (Sandbox Code Playgroud)

或者:

(s.sort_values(ascending=False) <= s.quantile(.5)).idxmax()
Run Code Online (Sandbox Code Playgroud)

我们可以将其功能化:

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

idxquantile(s)
Run Code Online (Sandbox Code Playgroud)


Joe*_*moe 5

如果您将interpolation参数设置为'lower', 'higher', 或者'nearest'则可以更简单地解决问题,如下所示:

s[s == s.quantile(.5, interpolation='lower')]
Run Code Online (Sandbox Code Playgroud)

我猜这个方法也比 piRSquared 的解决方案快一点