在Pandas数据框架中使用箱子

2024-10-03 11:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个总共有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列显示根据其所处的范围(使用)分配给每个数据点的bin编号pd.切割把柱子切成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

Tags: 数据代码inforbinbucketmin编号
1条回答
网友
1楼 · 发布于 2024-10-03 11:16:45

我将使用numpy中的两个函数,即np.linspace生成bin边界,并np.digitize将数据帧的值放入bin:

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

相关问题 更多 >