在《利用Python进行数据分析》这本书的第七章介绍了pandas的qcut函数的用法。原书介绍qcut函数是一个与分箱密切相关的函数,它基于样本分位数进行分箱,可以通过qcut获得等长的箱:
data = np.random.randn(1000)#data服从正态分布
cats = pd.qcut(data, 4)#将data均匀分成四份
cats
Out: [(0.657, 3.349], (-0.722, -0.0358], (-3.016, -0.722], (-3.016, -0.722], (-3.016, -0.722], ..., (-0.722, -0.0358], (-0.722, -0.0358], (-0.722, -0.0358], (-0.0358, 0.657], (-0.0358, 0.657]]
Length: 1000
Categories (4, interval[float64]): [(-3.016, -0.722] < (-0.722, -0.0358] < (-0.0358, 0.657] < (0.657, 3.349]]
pd.value_counts(cats)#使用qcut获得了等长的箱
Out: (0.657, 3.349] 250
(-0.0358, 0.657] 250
(-0.722, -0.0358] 250
(-3.016, -0.722] 250
dtype: int64
data里面的元素服从正态分布,长度为1000,qcut将data按照每250的数据量将data分箱,分出4个等长的箱
我们也可以传入自定义的分位数(0和1之间的数据)
pd.qcut(data, [0, 0.1, 0.5, 0.9, 1.])
Out: [(1