如何计算数组中各元素的百分位数?求NumPy可行方案
Got it, I totally get what you're asking for here—you want the percentile rank of each element in your sorted array, which is the reverse of what np.percentile does. Let's break down how to solve this easily.
方法1:纯NumPy实现(最直接高效)
Since your array is already sorted in ascending order, you can calculate the percentile rank directly using the position of each element. For an array of length n, the index of each element (starting from 0) divided by n-1 (since we're spanning from 0 to 100 percent across all elements) gives you the relative position, which you multiply by 100 to get the percentile.
Here's the code:
import numpy as np # 你的输入数组(已排序) arr = np.array([1, 2, 3, 4, 5]) n = len(arr) # 计算每个元素的百分位数 percentile_ranks = (np.arange(n) / (n - 1)) * 100 print(percentile_ranks) # 输出: [ 0. 25. 50. 75. 100.]
If your array isn't pre-sorted, just add a sorting step first, and if you need the results to match the original array's order, use argsort to map the ranks back:
arr = np.array([3, 1, 4, 2, 5]) sorted_arr = np.sort(arr) n = len(sorted_arr) # 计算排序后数组的百分位数 sorted_ranks = (np.arange(n) / (n - 1)) * 100 # 映射回原数组的顺序 original_indices = np.argsort(arr) result = np.empty_like(arr, dtype=float) result[original_indices] = sorted_ranks print(result) # 输出: [50. 0. 75. 25. 100.]
方法2:使用SciPy的percentileofscore
If you don't mind adding a SciPy dependency, you can use scipy.stats.percentileofscore with the kind='rank' parameter. This function calculates the percentile rank of each element relative to the entire array, and the rank kind ensures we get the 0-100 scale you need for unique sorted values:
from scipy import stats arr = np.array([1, 2, 3, 4, 5]) percentile_ranks = [stats.percentileofscore(arr, x, kind='rank') for x in arr] print(percentile_ranks) # 输出: [0.0, 25.0, 50.0, 75.0, 100.0]
为什么这两种方法有效?
The core idea here is that for a sorted array of n elements, the first element is at the 0th percentile (minimum), the last at the 100th (maximum), and each element in between is spaced evenly by 100/(n-1) percent. This matches exactly the output you're expecting.
内容的提问来源于stack exchange,提问作者Clock Slave

