1

我正在使用以下代码来计算给定数据集的四分位数:

#!/usr/bin/python

import numpy as np

series = [1,2,2,2,2,2,2,2,2,2,2,5,5,6,7,8]

p1 = 25
p2 = 50
p3 = 75

q1 = np.percentile(series,  p1)
q2 = np.percentile(series,  p2)
q3 = np.percentile(series,  p3)

print('percentile(' + str(p1) + '): ' + str(q1))
print('percentile(' + str(p2) + '): ' + str(q2))
print('percentile(' + str(p3) + '): ' + str(q3))

percentile 函数返回四分位数,但是,我还想获取它用来标记四分位数边界的索引。有没有办法做到这一点?

4

3 回答 3

1

Since the data is sorted, you could just use numpy.searchsorted to return the indices at which to insert the values to maintain sorted order. You can specify which 'side' to insert the values.

>>> np.searchsorted(series,q1)
1
>>> np.searchsorted(series,q1,side='right')
11
>>> np.searchsorted(series,q2)
1
>>> np.searchsorted(series,q3)
11
>>> np.searchsorted(series,q3,side='right')
13
于 2017-03-22T17:58:57.960 回答
0

尝试这个:

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]
thresholds = [25,50,75]
output = pd.DataFrame([np.percentile(series,x) for x in thresholds], index = thresholds, columns = ['quartiles'])
output

通过使其成为数据框,您可以非常轻松地分配索引。

于 2017-03-22T17:35:18.323 回答
0

假设数据总是排序的(感谢@juanpa.arrivillaga),您可以使用rankPandasSeries类中的方法。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
于 2017-03-22T17:45:29.533 回答