数据分箱技术Binning

数据分箱技术Binning

引入相关库

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

数据获取

产生一些考试的成绩分数,一共20个数据在25到100之间

score_list=np.random.randint(25,100,size=20)
score_list
array([66, 40, 32, 55, 81, 91, 49, 57, 36, 96, 83, 55, 98, 38, 36, 82, 71,
       39, 73, 60])

数据分箱

把0-59作为不及格,60-70作为ok,70-80作为良好,80-100作为优秀,定义一个list作为数据的取值范围

bins=[0,59,70,80,100]

通过cut方法,第一个参数为对哪个数据做分箱,第二个参数作为分箱的范围

pd.cut(score_list,bins)
[(59, 70], (0, 59], (0, 59], (0, 59], (80, 100], ..., (80, 100], (70, 80], (0, 59], (70, 80], (59, 70]]
Length: 20
Categories (4, interval[int64]): [(0, 59] < (59, 70] < (70, 80] < (80, 100]]
score_cat=pd.cut(score_list,bins)

统计每个分数段人数的结果

pd.value_counts(score_cat)
(0, 59]      10
(80, 100]     6
(70, 80]      2
(59, 70]      2
dtype: int64

创建一个空的DataFrame

df=DataFrame()

把‘score’这一列用score_list赋值

df['score']=score_list
df
score
066
140
232
355
481
591
649
757
836
996
1083
1155
1298
1338
1436
1582
1671
1739
1873
1960

通过rands生成随机的20个字符串,作为学生的姓名

df['student']=[pd.util.testing.rands(3) for i in range(20)]
df
scorestudent
066mDG
140pCe
232Iuv
355sWt
481eaR
5915Gw
6498Xc
757Tu2
836IRS
996VQU
1083lsc
1155nek
1298cFQ
1338ZeB
1436Lfi
1582jYv
1671x6q
1739t9I
1873CJg
1960hF4

把DataFrame的score作cut

pd.cut(df['score'],bins)
0      (59, 70]
1       (0, 59]
2       (0, 59]
3       (0, 59]
4     (80, 100]
5     (80, 100]
6       (0, 59]
7       (0, 59]
8       (0, 59]
9     (80, 100]
10    (80, 100]
11      (0, 59]
12    (80, 100]
13      (0, 59]
14      (0, 59]
15    (80, 100]
16     (70, 80]
17      (0, 59]
18     (70, 80]
19     (59, 70]
Name: score, dtype: category
Categories (4, interval[int64]): [(0, 59] < (59, 70] < (70, 80] < (80, 100]]

把做完cut的Categorie赋给DataFrame的‘Categories’

df['Categories ']=pd.cut(df['score'],bins)
df
scorestudentCategories
066mDG(59, 70]
140pCe(0, 59]
232Iuv(0, 59]
355sWt(0, 59]
481eaR(80, 100]
5915Gw(80, 100]
6498Xc(0, 59]
757Tu2(0, 59]
836IRS(0, 59]
996VQU(80, 100]
1083lsc(80, 100]
1155nek(0, 59]
1298cFQ(80, 100]
1338ZeB(0, 59]
1436Lfi(0, 59]
1582jYv(80, 100]
1671x6q(70, 80]
1739t9I(0, 59]
1873CJg(70, 80]
1960hF4(59, 70]

定义一个list,作为labels方法的参数,通过标签的方法,把Categories标志出来,更适合人的阅读

df['Categories ']=pd.cut(df['score'],bins,labels=['Low','OK','Good','Great'])
df
scorestudentCategories
066mDGOK
140pCeLow
232IuvLow
355sWtLow
481eaRGreat
5915GwGreat
6498XcLow
757Tu2Low
836IRSLow
996VQUGreat
1083lscGreat
1155nekLow
1298cFQGreat
1338ZeBLow
1436LfiLow
1582jYvGreat
1671x6qGood
1739t9ILow
1873CJgGood
1960hF4OK
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值