我有一个要转换为百分位数的数组。例如,假设我有一个正态分布的数组:

import numpy as np
import matplotlib.pyplot as plt

arr = np.random.normal(0, 1, 1000)
plt.hist(arr)

python - 将数组转换为百分位数-LMLPHP

对于该数组中的每个值,我想计算该值的百分位数(例如0是上述分布的第50个百分位数,所以0-> 0.5)。由于每个百分位数应具有相等的权重,因此结果应均匀分布。

python - 将数组转换为百分位数-LMLPHP

我找到了np.percentile,但是此函数在给定数组和分位数的情况下返回一个值,而我需要在给定数组和值的情况下返回一个分位数。

有没有相对有效的方法来做到这一点?

最佳答案

from scipy.stats import percentileofscore
import pandas as pd

# generate example data
arr = np.random.normal(0, 1, 10)

# pre-sort array
arr_sorted =  sorted(arr)

# calculate percentiles using scipy func percentileofscore on each array element
s = pd.Series(arr)
percentiles = s.apply(lambda x: percentileofscore(arr_sorted, x))

检查结果是否正确:
df = pd.DataFrame({'data': s, 'percentiles': percentiles})
df.sort_values(by='data')

       data   pcts
3 -1.692881   10.0
8 -1.395427   20.0
7 -1.162031   30.0
6 -0.568550   40.0
9  0.047298   50.0
5  0.296661   60.0
0  0.534816   70.0
4  0.542267   80.0
1  0.584766   90.0
2  1.185000  100.0

关于python - 将数组转换为百分位数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44607537/

10-11 22:12
查看更多