pandas:将数据分箱到特定数量的特定大小的箱中

pandas: bin data into specific number of bins of specific size

我想按单列中的值将数据帧分箱到特定大小和数量的分箱中。

这里有一个例子 df:

df= pd.DataFrame(np.random.randint(0,10000,size=(10000, 4)), columns=list('ABCD'))

说我要按D列分箱,我先对数据进行排序:

df.sort('D')

我现在希望分箱,如果分箱大小为 50 且分箱编号为 100,则前 50 个值将进入分箱 1,下一个进入分箱 2,依此类推。二十个箱子之后的任何剩余值都应该进入最后一个箱子。有办法吗?

编辑:

这是一个示例输入:

x = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))

这是预期的输出:

    A   B   C   D   bin
0   6   8   6   5   3
1   5   4   9   1   1
2   5   1   7   4   3
3   6   3   3   3   2
4   2   5   9   3   2
5   2   5   1   3   2
6   0   1   1   0   1
7   3   9   5   8   3
8   2   4   0   1   1
9   6   4   5   6   3

另外,是否也可以将任何相等的值放入同一个容器中?因此,例如,假设我有 bin 1,其中包含值 0,1,1,然后 bin 2 包含 1,1,2。有什么方法可以将 bin 2 中的这两个 1 值放入 bin 1 中吗?这会产生非常不均匀的 bin 大小,但这不是问题。

您似乎需要 floor divide np.arange 然后分配给新列:

idx = df['D'].sort_values().index
df['b'] = pd.Series(np.arange(len(df)) // 3 + 1, index = idx)
print (df)
   A  B  C  D  bin  b
0  6  8  6  5    3  3
1  5  4  9  1    1  1
2  5  1  7  4    3  3
3  6  3  3  3    2  2
4  2  5  9  3    2  2
5  2  5  1  3    2  2
6  0  1  1  0    1  1
7  3  9  5  8    3  4
8  2  4  0  1    1  1
9  6  4  5  6    3  3

详情:

print (np.arange(len(df)) // 3 + 1)
[1 1 1 2 2 2 3 3 3 4]

编辑:

我创建了另一个关于最后值问题的问题 :

N = 3
idx = df['D'].sort_values().index

#one possible solution, thanks divakar
def replace_irregular_groupings(a, N):
    n = len(a)
    m = N*(n//N)
    if m!=n:
        a[m:] = a[m-1]
    return a

idx = df['D'].sort_values().index
arr = replace_irregular_groupings(np.arange(len(df)) // N + 1, N)
df['b'] = pd.Series(arr, index = idx)
print (df)

   A  B  C  D  bin  b
0  6  8  6  5    3  3
1  5  4  9  1    1  1
2  5  1  7  4    3  3
3  6  3  3  3    2  2
4  2  5  9  3    2  2
5  2  5  1  3    2  2
6  0  1  1  0    1  1
7  3  9  5  8    3  3
8  2  4  0  1    1  1
9  6  4  5  6    3  3