You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas GroupBy apply创建新列时遇索引不兼容错误求助

解决方法

问题出在groupby.apply()的返回结果索引与原DataFrame不匹配:当你在lambda里执行x['Maths']/x['Physics']时,apply()会返回拼接后的分组结果,但这些结果的索引是分组内的局部索引,无法直接和原DataFrame的全局索引对齐,因此抛出TypeError: incompatible index of inserted column with frame index错误。而用固定值时,pandas会自动将标量广播到整个分组的行,索引自然匹配。

正确写法

使用groupby.transform()替代apply(),它会自动保证返回结果的索引与原DataFrame完全对齐:

df['Math/Physic'] = df.groupby(['Rank'], sort=False).transform(lambda x: x['Maths'] / x['Physics'])

额外说明

如果你的需求只是计算每行的Maths与Physics的比值,其实不需要分组,直接执行以下代码即可:

df['Math/Physic'] = df['Maths'] / df['Physics']

内容的提问来源于stack exchange,提问作者Prasanta Saha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 22:24:13