Bin随机值使用.cut()并将bin放在新的Pandas数据帧列中

问题描述 投票:1回答:1

能够完成功能和下面的循环?无法弄清楚如何将以下列合并,然后1)将分箱值放入新列,2).add_prefix()到前缀为“bin_”的每个新7列?无法弄清楚如何获得该功能和循环工作。

binner=list(range(0,6))
countofbins=len(binner)
df = pd.DataFrame(np.random.rand(20,7), columns=list('ABCDEFG'))
df['bin_A']=pd.cut(x=df['A'],bins=countofbins,labels=binner)

def calculate_bins(bincolumnname, oldcolumnname):
    for ind, column in enumerate(df.columns):
    df[bincolumnname] = pd.cut(x=df[oldcolumnname], bins=countofbins,labels=binner)
    return df[bincolumnname]
python-3.x pandas for-loop bucket
1个回答
1
投票

如果我理解正确,您正在尝试为数据框中包含每个单元所在的bin的每个列创建新列。

binner=list(range(0,6))
df = pd.DataFrame(np.random.randint(low=1, high=5,size=(20,7)), columns=list('ABCDEFG'))
for idx, col in enumerate(df.columns):
    df['bin_{}'.format(col)]=pd.cut(x=df.loc[:, col],bins=binner)

输出:

    A  B  C  D  E  F  G   bin_A   bin_B   bin_C   bin_D   bin_E   bin_F   bin_G
0   1  3  2  1  4  3  2  (0, 1]  (2, 3]  (1, 2]  (0, 1]  (3, 4]  (2, 3]  (1, 2]
1   1  1  3  2  4  4  4  (0, 1]  (0, 1]  (2, 3]  (1, 2]  (3, 4]  (3, 4]  (3, 4]
2   1  2  2  3  1  2  2  (0, 1]  (1, 2]  (1, 2]  (2, 3]  (0, 1]  (1, 2]  (1, 2]
3   1  1  1  2  2  1  3  (0, 1]  (0, 1]  (0, 1]  (1, 2]  (1, 2]  (0, 1]  (2, 3]
4   1  3  1  1  4  4  4  (0, 1]  (2, 3]  (0, 1]  (0, 1]  (3, 4]  (3, 4]  (3, 4]
5   4  3  3  1  1  3  1  (3, 4]  (2, 3]  (2, 3]  (0, 1]  (0, 1]  (2, 3]  (0, 1]
6   1  2  1  4  2  2  3  (0, 1]  (1, 2]  (0, 1]  (3, 4]  (1, 2]  (1, 2]  (2, 3]
7   4  2  2  1  3  2  3  (3, 4]  (1, 2]  (1, 2]  (0, 1]  (2, 3]  (1, 2]  (2, 3]
8   1  1  4  1  1  2  1  (0, 1]  (0, 1]  (3, 4]  (0, 1]  (0, 1]  (1, 2]  (0, 1]
9   3  1  4  1  3  2  4  (2, 3]  (0, 1]  (3, 4]  (0, 1]  (2, 3]  (1, 2]  (3, 4]
10  2  2  2  3  3  4  4  (1, 2]  (1, 2]  (1, 2]  (2, 3]  (2, 3]  (3, 4]  (3, 4]
11  1  2  1  1  4  3  3  (0, 1]  (1, 2]  (0, 1]  (0, 1]  (3, 4]  (2, 3]  (2, 3]
12  4  1  1  1  4  1  1  (3, 4]  (0, 1]  (0, 1]  (0, 1]  (3, 4]  (0, 1]  (0, 1]
13  1  2  4  4  2  4  3  (0, 1]  (1, 2]  (3, 4]  (3, 4]  (1, 2]  (3, 4]  (2, 3]
14  3  3  4  4  2  4  2  (2, 3]  (2, 3]  (3, 4]  (3, 4]  (1, 2]  (3, 4]  (1, 2]
15  1  4  1  3  2  2  3  (0, 1]  (3, 4]  (0, 1]  (2, 3]  (1, 2]  (1, 2]  (2, 3]
16  4  2  2  3  2  1  2  (3, 4]  (1, 2]  (1, 2]  (2, 3]  (1, 2]  (0, 1]  (1, 2]
17  1  2  3  4  3  2  3  (0, 1]  (1, 2]  (2, 3]  (3, 4]  (2, 3]  (1, 2]  (2, 3]
18  2  3  3  2  3  3  3  (1, 2]  (2, 3]  (2, 3]  (1, 2]  (2, 3]  (2, 3]  (2, 3]
19  2  4  1  1  3  2  4  (1, 2]  (3, 4]  (0, 1]  (0, 1]  (2, 3]  (1, 2]  (3, 4]

您可以使用labels中的pandas.cut()参数更改分档的标签

© www.soinside.com 2019 - 2024. All rights reserved.