在熊猫数据框中使用垃圾箱

时间:2018-10-26 07:41:47

标签: python pandas dataframe data-science data-cleaning

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

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列根据它们将落入的范围(使用pd.cut将列分成8等份)显示分配给每个数据点的bin编号。 在此先感谢!

样本数据

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

1 个答案:

答案 0 :(得分:0)

我将使用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