在 pandas 数据框中使用 bin

Using bins in pandas data frame

我正在处理一个总共有 4 列的数据框,我想将该数据框的每一列迭代地分成 8 个相等的部分。 bin 编号应分配给每列单独列中的数据。 即使为任何不同的数据框提供了不同的列名,该代码也应该可以工作。 这是我试过的代码。

for c in df3.columns:
    df3['bucket_' + c] = (df3.max() - df3.min()) // 2 + 1
    buckets = pd.cut(df3['bucket_' + c], 8, labels=False) 

sample data frame

expected output

相关的 bin 列显示分配给每个数据点的 bin 编号,根据它们将落入的范围(使用 pd.cut 将列分成 8 个等份)。 提前致谢!!

示例数据

gp1_min gp2 gp3 gp4

17.39   23.19   28.99   44.93

0.74    1.12    3.35    39.78

12.63   13.16   13.68   15.26

72.76   73.92   75.42   94.35

77.09   84.14   74.89   89.87

73.24   75.72   77.28   92.3

78.63   84.35   64.89   89.31

65.59   65.95   66.49   92.43

76.79   83.93   75.89   89.73

57.78   57.78   2.22    71.11

99.9    99.1    100      100

100     100    40.963855    100

预期输出

gp1_min gp2 gp3 gp4 bin_gp1 bin_gp2 bin_gp3 bin_gp4

17.39   23.19   28.99   44.93   2   2   2   3

0.74    1.12    3.35    39.78   1   1   1   3

12.63   13.16   13.68   15.26   1   2   2   2

72.76   73.92   75.42   94.35   5   6   6   7

77.09   84.14   74.89   89.87   6   7   6   7

73.24   75.72   77.28   92.3    6   6   6   7

78.63   84.35   64.89   89.31   6   7   5   7

65.59   65.95   66.49   92.43   5   6   5   7

76.79   83.93   75.89   89.73   6   7   6   7

57.78   57.78   2.22    71.11   4   4   1   6

99.9    99.1    100      100    8   8   8   8

100      100    40.96    100    8   8   3   8

我会使用 numpy 中的几个函数,即 np.linspace 来制作 bin 边界和 np.digitize 将数据帧的值放入 bins:

import numpy as np
def binner(df,num_bins):
    for c in df.columns:
        cbins = np.linspace(min(df[c]),max(df[c]),num_bins+1)
        df[c + '_binned'] = np.digitize(df[c],cbins)
    return df