numpy.quantile()
方法沿着指定的轴计算数据的q分位数。
示例
import numpy as np
# create an array
array1 = np.array([0, 1, 2, 3, 4, 5, 6, 7])
# calculate the 0.25th, 0.50th and 0.75th quantile of the array
q25 = np.quantile(array1, 0.25)
q50 = np.quantile(array1, 0.50)
q75 = np.quantile(array1, 0.75)
print(q25, q50, q75)
# Output: 1.75 3.5 5.25
quantile() 语法
numpy.quantile()
方法的语法是:
numpy.quantile(array, q, axis = None, out = None, overwrite_input = False, method = 'linear', keepdims = False, interpolation = None)
quantile() 参数
numpy.quantile()
方法接受以下参数:
array
- 输入数组(可以是array_like
)q
- 要查找的q分位数(可以是float
的array_like
)axis
(可选) - 计算分位数的轴或轴(int
或tuple of int
)out
(可选) - 用于存放结果的输出数组(ndarray
)keepdims
(可选) - 指定是否保留原始数组的形状(bool
)override_input
(可选) - 确定中间计算是否可以修改数组的bool
值method
(可选) - 要使用的插值方法interpolation
(可选) -method
关键字参数的已弃用名称
注意: numpy.quantile()
的默认值有以下含义:
axis = None
- 计算整个数组的分位数。- 默认情况下,
keepdims
和override_input
为False
。 - 插值方法为
'linear'
。 - 如果输入包含小于
float64
的整数或浮点数,则输出数据类型为float64
。否则,输出数据类型与输入数据类型相同。
quantile() 返回值
numpy.quantile()
方法沿指定轴返回输入数组的q分位数。
分位数
分位数是一种统计量,表示数据低于该值的百分比。它有助于分析数据集的分布。
在 NumPy 中,quantile()
函数计算沿指定轴的数据的q分位数。
q分位数表示数据中有q%的数据小于该值。例如,0.50分位数(也称为中位数)将数据分成两半。
注意:numpy.quantile()
和 numpy.percentile()
功能相同。如果要指定 q
的范围为 0 到 100,请使用 percentile()
;如果要指定 q
的范围为 0.0 到 1.0,请使用 quantile()
。
示例 1:查找 ndArray 的分位数
import numpy as np
# create an array
array1 = np.array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
# find the 50th quantile of entire array
quantile1 = np.quantile(array1, q = 0.50)
# find the 50th quantile across axis 0
quantile2 = np.quantile(array1, q = 0.50, axis = 0)
# find the 50th quantile across axis 0 and 1
quantile3 = np.quantile(array1, q = 0.50, axis = (0, 1))
print('\n50th quantile of the entire array:', quantile1)
print('\n50th quantile across axis 0:\n', quantile2)
print('\n50th quantile across axis 0 and 1:', quantile3)
输出
50th quantile of the entire array: 3.5 50th quantile across axis 0: [[2. 3.] [4. 5.]] 50th quantile across axis 0 and 1: [3. 4.]
示例 2:使用可选的 out 参数
out
参数允许我们指定一个输出数组来存储结果。
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# create an output array
output = np.zeros(3)
# compute 25th quantile and store the result in the output array
np.quantile(arr, 0.25, out = output, axis = 0)
print('25th quantile:', output)
输出
25th quantile: [1.75 2.75 3.75]
示例 3:使用可选的 keepdims 参数
如果 keepdims
设置为 True
,则结果数组的维度与原始数组相同。
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# keepdims defaults to False
result1 = np.quantile(arr, 0.50 , axis = 0)
# pass keepdims as True
result2 = np.quantile(arr, 0.50, axis = 0, keepdims = True)
print('Dimensions in original array:', arr.ndim)
print('Without keepdims:', result1, 'with dimensions', result1.ndim)
print('With keepdims:', result2, 'with dimensions', result2.ndim)
输出
Dimensions in original array: 2 Without keepdims: [2.5 3.5 4.5] with dimensions 1 With keepdims: [[2.5 3.5 4.5]] with dimensions 2