numpy

常用

np.percentile

np.percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)

计算沿指定轴的数组元素的第 q 个百分位数,首先沿轴计算index的区间,然后对数值进行插值。

参数:

  • a: 输入数组。
  • q: 要计算的百分位数,介于 0 和 100 之间(含)。
  • axis: 沿着它计算百分位数的轴。如果为 None,则对展平的数组计算百分位数。
  • out: 替代输出数组,用于放置结果。
  • overwrite_input: 如果为 True,则允许输入数组 a 被修改。这可以节省内存,但会改变原始输入。
  • interpolation: 当所需的百分位数落在两个数据点之间时,指定要使用的插值方法。
    • 'lower': 返回两个数据点中较小的一个。
    • 'higher': 返回两个数据点中较大的一个。
    • 'nearest': 返回最近的数据点。
    • 'midpoint': 返回 lowerhigher 的平均值。
    • 'linear': 默认值,线性插值。
  • keepdims: 如果设置为 True,则轴在结果中保留为大小为一的维度。

示例:

import numpy as np

a = np.array([[10, 7, 4], [3, 2, 1]])

# 计算展平数组的第 50 个百分位数 (中位数)
p50 = np.percentile(a, 50)
print(f"50th percentile of flattened array: {p50}") # Output: 3.5

# 沿着 axis=0 计算第 50 个百分位数
p50_axis0 = np.percentile(a, 50, axis=0)
print(f"50th percentile along axis 0: {p50_axis0}") # Output: [6.5 4.5 2.5]

# 沿着 axis=1 计算第 50 个百分位数
p50_axis1 = np.percentile(a, 50, axis=1)
print(f"50th percentile along axis 1: {p50_axis1}") # Output: [7. 2.]

# 使用不同的插值方法
p50_higher = np.percentile(a, 50, interpolation='higher')
print(f"50th percentile with 'higher' interpolation: {p50_higher}") # Output: 4

# 计算第 25 和 75 个百分位数
p25_75 = np.percentile(a, [25, 75])
print(f"25th and 75th percentiles: {p25_75}") # Output: [2.25 6.75]