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

Pandas数据处理:仅保留ID首行的0值,删除其余行的0值

解决方案

直接用Pandas的分组计数结合布尔筛选就能搞定,不用写循环,效率更高也不容易出错。

步骤说明

  1. 给每个ID分组的行标记序号:用groupby('ID').cumcount()给每组行从0开始计数,首行的序号为0。
  2. 筛选符合条件的行:保留两种情况的行——要么Tenure不为0,要么是分组首行且Tenure为0。

代码实现

先构造输入示例方便测试:

import pandas as pd

# 输入示例
df = pd.DataFrame({
    'ID': [1,1,1,2,2,3,3,3],
    'Tenure': [0, 0, 5, 3, 0, 0, 2, 0],
    'OtherCol': ['a','b','c','d','e','f','g','h']
})

# 核心筛选逻辑
filtered_df = df[
    (df['Tenure'] != 0) | 
    (df.groupby('ID').cumcount() == 0) & (df['Tenure'] == 0)
]

print(filtered_df)

输出结果

ID  Tenure OtherCol
0   1       0        a
2   1       5        c
3   2       3        d
5   3       0        f
6   3       2        g

这个方法完全符合需求:每个ID分组仅保留首行的Tenure=0,其他位置的Tenure=0全部删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:50:17