groupby 和将列乘以标量

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

我写了这段代码:

tmp_ml['mode_dur_secs_lb'] = tmp_ml.groupby(['id', 'c_num']).apply(
    lambda x: x['mode_duration_secs']*0.9)

表:

id c_num 模式_持续时间_秒
a1 116 20
a1 279 3
a2 9 19
a3 16 16
a3 17 19

类型错误:插入列的索引与框架索引不兼容

python pandas group-by
1个回答
0
投票

假设您的函数是一个虚拟函数,您必须将

group_keys=False
传递给
groupby
以避免将分组列设置为索引:

tmp_ml['mode_dur_secs_lb'] = (tmp_ml.groupby(['id', 'c_num'], group_keys=False)
                                    .apply(lambda x: x['mode_duration_secs']*0.9,
                                           include_groups=False)
                             )

如果这是你的实际功能,那么

groupby
没用,只需:

tmp_ml['mode_dur_secs_lb'] = tmp_ml['mode_duration_secs']*0.9

输出:

   id  c_num  mode_duration_secs  mode_dur_secs_lb
0  a1    116                  20              18.0
1  a1    279                   3               2.7
2  a2      9                  19              17.1
3  a3     16                  16              14.4
4  a3     17                  19              17.1
© www.soinside.com 2019 - 2024. All rights reserved.