pandas - qcut()和cut()区别

本文详细介绍了pandas中的cut()和qcut()函数。cut()根据值的区间进行均匀间隔划分,而qcut()则依据值的频率进行等频划分。通过实例展示了如何使用这两个函数进行数据分段,例如对成绩进行优良差统计和四分位数划分。
摘要由CSDN通过智能技术生成
cut()

定义:cut返回 x 中的每一个数据在bins中对应的范围。根据值本身来选择箱子均匀间隔,即每个箱子的间距都是相同的。

语法:

pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False)

参数:

  • x : 必须是一维数据
  • bins: 不同面元(不同范围)类型:整数,序列如数组, 和IntervalIndex
  • right: 最后一个bins是否包含最右边的数据,默认为True
  • precision:精度 默认保留三位小数
  • retbins: 即return bins 是否返回每一个bins的范围 默认为False

例子:实现成绩的优良差统计

import numpy as np
import pandas as pd

scores = np.random.uniform(0,100,size=30).astype('int')
# 指定分箱的区间
grades = [0,59,70,85,100]
boxs = pd.cut(scores,grades)
boxs.value_counts()
#output:
(0, 59]      16
(59, 70]      1
(70, 85]      5
(85, 100]     8
dtype: int64

# 传入label来自定义箱名
group_names = ['不及格','及格','良','优秀']
boxs= pd.cut(scores,grades,labels=group_names)
boxs.value_counts()
#output:
不及格    16
及格      15
优秀      8
dtype: int64

# 将成绩均匀的分在四个箱子中,precision=2的选项将精度控制在两位
boxs = pd.cut(scores,4,precision=2)
boxs.value_counts()
#output:
(2.91, 26.5]     6
(26.5, 50.0]     6
(50.0, 73.5]     5
(73.5, 97.0]    13
dtype: int64
qcut()

定义:qcut是根据这些值的频率来选择箱子的均匀间隔,每个箱子中含有的数的数量是相同的。

语法:

pandas.qcut(x, q, labels=None, retbins=False, precision=3, duplicates=raise)

参数:

  • x: 是数据ndarray或Series
  • q:整数或分位数数组;定义区间分割方法
    分位数10为十分位数,4为四分位数等。或分位数组,如四分位数 [0, 0.25, 0.5, 0.75, 1] 分成两半[0, 0.5, 1]

例子:将成绩平均分为四份/按照四分位对成绩划分

scores = np.random.uniform(0,100,size=40).astype('int')

# 平分四组数
boxs = pd.qcut(scores,4)
boxs.value_counts()
#output:
(0.999, 23.75]    10
(23.75, 55.0]     10
(55.0, 76.5]      10
(76.5, 99.0]      10
dtype: int64

# 设定label
boxs = pd.qcut(scores,4,labels=['s1','s2','s3','s4'])
boxs.value_counts()
#output:
s1    10
s2    10
s3    10
s4    10
dtype: int64

# 设定等分位分箱
boxs = pd.qcut(scores,[0, 0.1, 0.2, 0.3, 1])
boxs.value_counts()
# output:
(0.999, 13.8]     4
(13.8, 22.6]      4
(22.6, 30.6]      4
(30.6, 99.0]     28
dtype: int64

#输出元祖
boxs = pd.qcut(scores,[0, 0.1, 0.2, 0.3, 1],labels=['s1','s2','s3','s4'],retbins=True)
boxs[0].value_counts()
#output:
s1     4
s2     4
s3     4
s4    28
dtype: int64
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值