NumPy的实用函数整理之percentile
NumPy函数percentile()用于计算指定维度上数组元素的第 n 个百分位数,返回值为标量或者数组。
percentile()
percentile(a, q, axis=None, out=None,overwrite_input=False, interpolation=linear, keepdims=False)
其中参数 a:numpy数组,待求分位数的数组,或者可以被转换为numpy数组的数据结构。 q:numpy数组或者百分位数,必须在0到100之间。 axis:索要求分位数的维度,默认None是所有数中求出分位数,axis=0是按列求分位数,axis=1是按行求分位数。 out:结果输出到某个变量,该变量必须有与返回结果相同的维度。 overwrite_input:布尔值,是否允许覆盖输入,默认为False。 interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’},此可选参数指定要使用的插值方法,当所需百分比位于两个数据点之间时使用i<j。
-
‘linear’: i + (j - i) * fraction,fraction介于0.5到1之间 ‘lower’: i ‘higher’: j ‘nearest’: i or j, 最近原则. ‘midpoint’: (i + j) / 2.
keepdims : 布尔值,默认为False,如果设置为True,那么输出就会与输入数组a保持相同的维度。
函数返回值:
标量或者numpy数组。如果q是单个百分位数和axis = none,则结果返回标量。如果给出了多个百分比,则返回多个分位数或分位数组。
举例如下:
输入:
a = np.array([[10, 7, 4], [3, 2, 1]]) a
输出:
array([[10, 7, 4], [ 3, 2, 1]])
例一:
输入:
np.percentile(a, 50)
输出:
3.5
例二:
输入:
np.percentile(a, [50,90])
输出:
array([3.5, 8.5])
例三: 输入:
np.percentile(a, 50, axis=0)
输出:
array([6.5, 4.5, 2.5])
输入:
np.percentile(a, [50,90], axis=0)
输出
array([[6.5, 4.5, 2.5], [9.3, 6.5, 3.7]])
例四: 输入:
np.percentile(a, 50, axis=0).shape
输出:
(3,)
输入:
np.percentile(a, 50, axis=0, keepdims=True).shape
输出:
(1, 3)
例五: 输入:
import matplotlib.pyplot as plt a = np.arange(4) p = np.linspace(0, 100, 6001) ax = plt.gca() lines = [ (linear, None), (higher, --), (lower, --), (nearest, -.), (midpoint, -.), ] for interpolation, style in lines: ax.plot( p, np.percentile(a, p, interpolation=interpolation), label=interpolation, linestyle=style) ax.set( title=Interpolation methods for list: + str(a), xlabel=Percentile, ylabel=List item returned, yticks=a) ax.legend() plt.show()
输出: 