等距分箱

python 自带的等宽分箱函数pd.cut()

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

score_list=np.random.randint(30,100,size=20)
print(score_list)
bins=[0,59,70,80,100]
score_cat=pd.cut(score_list,bins)
print(score_cat)

 

自定义实现


def create_bins(lower_bound,width,quantity):
    bins=[]
    for low in range(lower_bound,lower_bound+quantity*width+1,width):
        bins.append((low,low+width))
    return bins
bins=create_bins(lower_bound=50,width=4,quantity=10)
print(bins)

def find_bin(value,bins):
    '''
   查找分箱
    '''
    for i in range(0,len(bins)):
        if bins[i][0] <=value<bins[i][1]:
            return i
    return -1
from collections import Counter
weight_of_persons=[49,73.4, 69.3, 64.9, 75.6, 74.9, 80.3,
                      78.6, 84.1, 88.9, 90.3, 83.4, 69.3,
                      52.4, 58.3, 67.4, 74.0, 89.3, 63.4]
binned_weight=[]
for value in weight_of_persons:
    bin_index=find_bin(value,bins)
    print(value,bin_index,bins[bin_index])
    binned_weight.append(bin_index)
frequencies=Counter(binned_weight)
print(frequencies)

[(50, 54), (54, 58), (58, 62), (62, 66), (66, 70), (70, 74), (74, 78), (78, 82), (82, 86), (86, 90), (90, 94)]
49 -1 (90, 94)
73.4 5 (70, 74)
69.3 4 (66, 70)
64.9 3 (62, 66)
75.6 6 (74, 78)
74.9 6 (74, 78)
80.3 7 (78, 82)
78.6 7 (78, 82)
84.1 8 (82, 86)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值