【python】numpy.percentile()函数

本文详细解析了numpy.percentile()函数的使用方法,包括其参数含义、百分位数的概念及计算方式,并通过实例展示了如何在不同轴上计算百分位数,以及保持维度不变的选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

numpy.percentile()

1.函数

百分位数是统计中使用的度量,表示小于这个值的观察值的百分比。 函数numpy.percentile()接受以下参数。

np.percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False) 
2.参数说明:
  • a: 输入数组
  • q: 要计算的百分位数,在 0 ~ 100 之间
  • axis: 沿着它计算百分位数的轴
  • keepdims :bool是否保持维度不变
  • 首先明确百分位数:第 p 个百分位数是这样一个值,它使得至少有 p% 的数据项小于或等于这个值,且至少有 (100-p)% 的数据项大于或等于这个值。

【注】举个例子:高等院校的入学考试成绩经常以百分位数的形式报告。比如,假设某个考生在入学考试中的语文部分的原始分数为 54 分。相对于参加同一考试的其他学生来说,他的成绩如何并不容易知道。但是如果原始分数54分恰好对应的是第70百分位数,我们就能知道大约70%的学生的考分比他低,而约30%的学生考分比他高。这里的 p = 70。

  • a : array_like
    Input array or object that can be converted to an array.
  • q : array_like of float
    Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive.
  • axis : {int, tuple of int, None}, optional
    Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array.
    Changed in version 1.9.0: A tuple of axes is supported
  • out : ndarray, optional
    Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.
  • overwrite_input : bool, optional
    If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.
  • interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}
    This optional parameter specifies the interpolation method to use when the desired percentile lies between two data points i < j:
    ‘linear’: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.
    ‘lower’: i.
    ‘higher’: j.
    ‘nearest’: i or j, whichever is nearest.
    ‘midpoint’: (i + j) / 2.
    New in version 1.9.0.
  • keepdims : bool, optional
    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.
3.实例分析
import numpy as np 
 
a = np.array([[10, 7, 4], [3, 2, 1]])
print ('我们的数组是:')
print (a)
 
print ('调用 percentile() 函数:')
# 50% 的分位数,就是 a 里排序之后的中位数
print (np.percentile(a, 50)) 
 
# axis 为 0,在纵列上求
print (np.percentile(a, 50, axis=0)) 
 
# axis 为 1,在横行上求
print (np.percentile(a, 50, axis=1)) 
 
# 保持维度不变
print (np.percentile(a, 50, axis=1, keepdims=True))

输出结果

我们的数组是:
[[10  7  4]
 [ 3  2  1]]
调用 percentile() 函数:
3.5
[6.5 4.5 2.5]
[7. 2.]
[[7.]
 [2.]]
4.更多例子
>> 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, axis=0)
array([6.5, 4.5, 2.5])
>>> np.percentile(a, 50, axis=1)
array([7.,  2.])
>>> np.percentile(a, 50, axis=1, keepdims=True)
array([[7.],
      [2.]])
>>> m = np.percentile(a, 50, axis=0)
>>> out = np.zeros_like(m)
>>> np.percentile(a, 50, axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
>>> b = a.copy()
>>> np.percentile(b, 50, axis=1, overwrite_input=True)
array([7.,  2.])
>>> assert not np.all(a == b)

参考:
1.https://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html
2.https://www.runoob.com/numpy/numpy-statistical-functions.html

VaR (Value at Risk) 是衡量金融投资风险的一种常用指标。在 Python 中,你可以使用各种库来计算 VaR。以下是使用常见库的示例: 1. 使用 `numpy` 和 `pandas` 库计算 VaR: ```python import numpy as np import pandas as pd # 假设有一个投资组合的收益率数据存储在 DataFrame 中 portfolio_returns = pd.DataFrame({'stock1': [0.05, -0.02, 0.03, -0.01, 0.02], 'stock2': [-0.03, 0.01, 0.02, -0.02, 0.04]}) # 计算每个股票的 VaR(以置信水平为 95%) conf_level = 0.95 portfolio_var = portfolio_returns.cov() # 计算协方差矩阵 portfolio_mean = portfolio_returns.mean() # 计算收益率均值 # 使用逆正态分布函数计算 VaR portfolio_var = np.array(portfolio_var) portfolio_mean = np.array(portfolio_mean) z_score = np.percentile(np.random.normal(0, 1, 10000), q=conf_level*100) portfolio_var = np.sqrt(np.dot(np.dot(portfolio_mean.T, portfolio_var), portfolio_mean)) * z_score print("Portfolio VaR:", portfolio_var) ``` 2. 使用 `pyfolio` 库计算 VaR: ```python import pyfolio as pf # 假设有一个投资组合的收益率数据存储在 DataFrame 中 portfolio_returns = pd.DataFrame({'stock1': [0.05, -0.02, 0.03, -0.01, 0.02], 'stock2': [-0.03, 0.01, 0.02, -0.02, 0.04]}) # 计算投资组合的 VaR(以置信水平为 95%) portfolio_var = pf.var.mean_historic(portfolio_returns, frequency=1, sigma=1, level=5) print("Portfolio VaR:", portfolio_var) ``` 这些示例代码可以帮助你计算投资组合的 VaR。请注意,VaR 的计算方法可能因具体需求而有所不同,以上代码仅提供一种常见的计算方式。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值