pandas的quantile函数

本文介绍了pandas的quantile函数,用于计算数据的分位数,特别是中位数。通过示例详细解释了如何计算不同分位数,并提到了参数如q、axis和interpolation的作用。此外,还提及了numpy的numpy.quantile函数,其用法与pandas类似。

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

pandas的quantile函数

  • quantile : 分位数的意思
    一般为 0.25 0.5 0.75分位数
  • 中数值的计算方法
    1. 设分位数为p : 分位数的值 = 1 + (n - 1) * p, n为数值的个数
    2. 看下面示例的计算
# quantile函数
DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation=’linear’)
  • 参数意义
    • q : 数字或者是类列表,范围只能在0-1之间,默认是0.5,即中位数-第2四分位数
    • axis :计算方向,可以是 {0, 1, ‘index’, ‘columns’}中之一,默认为 0
    • interpolation(插值方法):可以是 {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}之一,默认是linear。
这五个插值方法是这样的:当选中的分为点位于两个数数据点 i and j 之间时:
linear: i + (j - i) * fraction, fraction由计算得到的pos的小数部分(后面有例子);
lower: i.
higher: j.
nearest: i or j whichever is nearest.
midpoint: (i + j) / 2.

示例1 : 分位数的计算

import pandas as pd
data = pd.DataFrame({'num':[2,4,7,8,9,10]})
data
num
02
14
27
38
49
510
print(data['num'].quantile()) # 默认0.5时,方法为liner
print(data['num'].quantile(interpolation="higher"))
7.5
8
  • 为什么是7.5 , 8?

      1. 中位数的位置 1 + (6-1) * 0.5 = 3.5,位于第3个数和第4个数之间,分别是 7 和 8
      1. liner : 7 + (8-7) * 0.5 = 7.5, (是(8-7)*3.5的小数部分0.5 )

      lower : 就是第3个数作为分位数,也就是7

      height : 就是8

      midpoint : (7 + 8)/ 2 = 7.5

      nearest : 不晓得

示例2 : 直接计算多个分位数

data['num'].quantile([0.25,0.5,0.75])
0.25    4.75
0.50    7.50
0.75    8.75
Name: num, dtype: float64

numpy中的numpy.quantile

numpy.quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation=‘linear’, keepdims=False)

  • 其中a为想要计算分位数的数据,其他和pandas中的基本相同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值