我想计算两个百分位数范围之间的平均数,例如第25和第50个百分位数之间的平均数,我通常使用np.percentile来计算具体的百分位数。
我通常使用np.percentile来计算具体的百分位值。
请问如何计算平均数(25-50)?我可以用减法吗?
mean(25-50) = np.percentile(array,50) - np.percentile(array,25)
``
你不能简单地将不同百分位的两个值相减。
为了找到第25和第50百分位之间的元素的平均值,你需要找到所有这些元素的总和,然后除以大小。
为了找到上述元素的和,你可以从0-25百分位元素的和中减去0-50百分位元素的和。
一旦你有了差值之和,只需将它除以这些元素的大小即可。
# find the indexes of the element below 25th and 50th percentile
idx_under_25 = np.argwhere(array <= np.percentile(array, 25)).ravel()
idx_under_50 = np.argwhere(array <= np.percentile(array, 50)).ravel()
# find the number of the elements in between 25th and 50th percentile
diff_num = len(idx_under_50) - len(idx_under_25)
# find the sum difference
diff_sum = np.sum(np.take(array, idx_50)) - np.sum(np.take(array, idx_25))
# get the mean
mean = diff_sum / diff_num