手动逐步计算 Numpy 百分位数:
第 1 步:查找长度
x = [1,2,3,4,5,6,7,8,9,10]
l = len(x)
# Output --> 10
第 2 步:减去1
以获得从第一个项目到最后一个项目的距离x
# n = (length - 1)
# n = (10-1)
# Output --> 9
第 3 步:乘以n
分位数,这里是第 25 个百分位数或 0.25 个分位数或第一个四分位数
n * 0.25
# Therefore, (9 * 0.25)
# Output --> 2.25
# So, fraction is 0.25 part of 2.25
# m = 0.25
Step-4 : 现在得到最终答案
对于线性:
# i + (j - i) * m
# Here, think i and j as values at indices
# x = [1,2,3,4,5,6,7,8,9,10]
#idx= [0,1,2,3,.........,9]
# So, for '2.25':
# value at index immediately before 2.25, is at index=2 so, i=3
# value at index immediately after 2.25, is at index=3 so, i=4
# and fractions
3 + (4 - 3)*0.25
# Output --> 3.25
对于较低:
# Here, based on output from Step-3
# Because, it is '2.25',
# Find a number a index lower than 2.25
# So, lower index is '2'
# x = [1,2,3,4,5,6,7,8,9,10]
#idx= [0,1,2,3,.........,9]
# So, at index=2 we have '3'
# Output --> 3
对于更高:
# Here, based on output from Step-3
# Because, it is '2.25',
# Find a number a index higher than 2.25
# So, higher index is '3'
# x = [1,2,3,4,5,6,7,8,9,10]
#idx= [0,1,2,3,.........,9]
# So, at index=3 we have '4'
# Output --> 4
对于最近的:
# Here, based on output from Step-3
# Because, it is '2.25',
# Find a number a index nearest to 2.25
# So, nearest index is '2'
# x = [1,2,3,4,5,6,7,8,9,10]
#idx= [0,1,2,3,.........,9]
# So, at index=2 we have '3'
# Output --> 3
对于中点:
# Here, based on output from Step-3
# (i + j)/2
# Here, think i and j as values at indices
# x = [1,2,3,4,5,6,7,8,9,10]
#idx= [0,1,2,3,.........,9]
# So, for '2.25'
# value at index immediately before 2.25, is at index=2 so, i=3
# value at index immediately after 2.25, is at index=3 so, i=4
(3+4)/2
# Output --> 3.5
Python中的代码:
x = np.array([1,2,3,4,5,6,7,8,9,10])
print("linear:", np.percentile(x, 25, interpolation='linear'))
print("lower:", np.percentile(x, 25, interpolation='lower'))
print("higher:", np.percentile(x, 25, interpolation='higher'))
print("nearest:", np.percentile(x, 25, interpolation='nearest'))
print("midpoint:", np.percentile(x, 25, interpolation='midpoint'))
输出:
linear: 3.25
lower: 3
higher: 4
nearest: 3
midpoint: 3.5