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

如何将DataFrame分组后每组指定列的首行值替换为0

按分组替换首行指定列值为0的Pandas实现

原始数据

import pandas as pd

df = pd.DataFrame({
    'Id': ['A1', 'A1', 'A1', 'B1', 'B1'],
    'status': ['clear', 'in-process', 'done', 'start', 'end'],
    'value': [23, 50, 20, 2, 30]
})

需求

按Id分组后,将每组中value列的首行值替换为0。

解决方案

用groupby结合cumcount()定位每组首行,直接赋值修改:

# cumcount()给每组内的行从0开始计数,等于0的就是组内第一行
df.loc[df.groupby('Id').cumcount() == 0, 'value'] = 0

最终结果

执行代码后得到的DataFrame如下:

Id      status  value
0  A1       clear      0
1  A1  in-process     50
2  A1        done     20
3  B1       start      0
4  B1         end     30

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:25:22