将数据分箱到大小相同的箱中
Binning data into equally sized bins
我想将值分到同样大小的分箱中。假设我们有以下 Pandas 系列:
ex = pd.Series([1,2,3,4,5,6,7,888,999])
现在,我想创建三个垃圾箱:
pd.cut(ex, 3, labels=False)
这导致三个 bin 和以下分配给系列中每个元素的 bin 编号:
[0,0,0,0,0,0,0,2,2]
现在,我想要 bin 边界,使每个 bin 具有相同数量的元素(即 3),并且将数据点分配给 bin 应该如下所示:
[0,0,0,1,1,1,2,2,2]
我怎样才能做到这一点?打破平局应该怎么做(即当数据点的数量不能被 bin 的数量整除时)?
试试
bins = ex.index//3 # np.arange(len(ex))//3
bins
Out[98]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype='int64')
使用-
pd.qcut(ex, 3, labels=False)
输出
0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
使用 retbins=True
获取垃圾箱。
pd.qcut(ex, 3, labels=False, retbins=True)
输出
(0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
dtype: int64,
array([ 1. , 3.66666667, 6.33333333, 999. ]))
改用pandas qcut函数。试试这个 pd.qcut(ex,q=3,labels=False)
我想将值分到同样大小的分箱中。假设我们有以下 Pandas 系列:
ex = pd.Series([1,2,3,4,5,6,7,888,999])
现在,我想创建三个垃圾箱:
pd.cut(ex, 3, labels=False)
这导致三个 bin 和以下分配给系列中每个元素的 bin 编号:
[0,0,0,0,0,0,0,2,2]
现在,我想要 bin 边界,使每个 bin 具有相同数量的元素(即 3),并且将数据点分配给 bin 应该如下所示:
[0,0,0,1,1,1,2,2,2]
我怎样才能做到这一点?打破平局应该怎么做(即当数据点的数量不能被 bin 的数量整除时)?
试试
bins = ex.index//3 # np.arange(len(ex))//3
bins
Out[98]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype='int64')
使用-
pd.qcut(ex, 3, labels=False)
输出
0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
使用 retbins=True
获取垃圾箱。
pd.qcut(ex, 3, labels=False, retbins=True)
输出
(0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
dtype: int64,
array([ 1. , 3.66666667, 6.33333333, 999. ]))
改用pandas qcut函数。试试这个 pd.qcut(ex,q=3,labels=False)