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

如何在Python中按条件分组生成起始为1的迭代编号

按分组生成起始值为1的Status累加列

需求说明

现有包含Product和Status列的表格,需生成第三列Values,满足以下要求:

  • Values为Status列的累加值,但起始值为1而非0;
  • 按Product列分组执行该累加操作。

SAS实现代码

if first.product then do; 
    values = 1;
end; 
if status = 1 then do; 
    values = values + 1; 
end; 

Python测试数据生成代码

import pandas as pd

df = pd.DataFrame({
    'Product': ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b'],
    'Status': [0, 1, 1, 0, 1, 1, 1, 1, 1],
}).set_index('Product')

预期输出

expected_output = pd.DataFrame({
    'Product': ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b'],
    'Status': [0, 1, 1, 0, 1, 1, 1, 1, 1],
    'Values': [1, 2, 3, 1, 2, 3, 4, 5, 6]
}).set_index('Product')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:59:57