为了账号安全,请及时绑定邮箱和手机立即绑定

基于 bin 创建列

基于 bin 创建列

狐的传说 2021-07-23 18:19:05
我有一个数据:# dtColumn1           1      2      3      4      5      6      7      8      9我想通过 bin 的最小值和最大值的平均值创建一个新列。# dtColumn1    Column2      1          2      2          2      3          2      4          5      5          5      6          5      7          8      8          8      9          8pd.qcut(dt['Column1'], 3)所以 column2 = (bin 的最小值 + bin 的最大值)/2。
查看完整描述

1 回答

?
慕仙森

TA贡献1827条经验 获得超8个赞

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  Column2

0        1      2.0

1        2      2.0

2        3      2.0

3        4      5.0

4        5      5.0

5        6      5.0

6        7      8.0

7        8      8.0

8        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 Column1

0        1          2.0

1        2          2.0

2        3          2.0

3        4          5.0

4        5          5.0

5        6          5.0

6        7          8.0

7        8          8.0

8        9          8.0


查看完整回答
反对 回复 2021-07-28
  • 1 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号