基于 bin 创建列

我有一个数据:


# dt

Column1     

      1

      2

      3

      4

      5

      6

      7

      8

      9

我想通过 bin 的最小值和最大值的平均值创建一个新列。


# dt

Column1    Column2

      1          2

      2          2

      3          2

      4          5

      5          5

      6          5

      7          8

      8          8

      9          8


pd.qcut(dt['Column1'], 3)

所以 column2 = (bin 的最小值 + bin 的最大值)/2。


狐的传说
浏览 146回答 1
1回答

慕仙森

GroupBy.transform与 lambda 函数Series一起使用以返回与原始大小相同的大小DataFrame:dt['Column2'] = (dt.groupby(pd.qcut(dt['Column1'], 3))['Column1']                   .transform(lambda x: x.max() + x.min()) / 2)或者使用 doubletransform和addand div:g = dt.groupby(pd.qcut(dt['Column1'], 3))dt['Column2'] = g['Column1'].transform('max').add(g['Column1'].transform('min')).div(2)print (dt)   Column1  Column20        1      2.01        2      2.02        3      2.03        4      5.04        5      5.05        6      5.06        7      8.07        8      8.08        9      8.0编辑:cols = ['Column1']for col in cols:    dt[f'New {col}'] = (dt.groupby(pd.qcut(dt[col], 3))[col]                       .transform(lambda x: x.max() + x.min()) / 2)print (dt)   Column1  New Column10        1          2.01        2          2.02        3          2.03        4          5.04        5          5.05        6          5.06        7          8.07        8          8.08        9          8.0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python