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

Python:按id分组后筛选DataFrame中speed超阈值行之前的所有行

Pandas按分组筛选首个超阈值行之前的所有数据

需求描述

给定一个包含多特征的DataFrame,需按id字段分组:

  • 对每个分组,识别speed字段值首次超过阈值(示例中阈值设为1.5)的行
  • 筛选并保留该行之前的所有行

输入示例

idspeed...
11.2...
11.9...
11.0...
50.9...
51.3...
53.5...
50.4...

期望输出

idspeed...
11.2...
50.9...
51.3...

解决方案

方法一:利用groupby+cumsum实现快速筛选

该方法效率较高,适合处理大数据集:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'id': [1,1,1,5,5,5,5],
    'speed': [1.2,1.9,1.0,0.9,1.3,3.5,0.4],
    'other_col': ['...']*7
})

threshold = 1.5

# 生成筛选掩码:保留每个分组中首个超阈值行之前的所有行
mask = df.groupby('id')['speed'].apply(lambda x: (x > threshold).cumsum() == 0)
result = df[mask]

print(result)

方法二:分组后定位首个超阈值行并切片

逻辑更直观,适合需要自定义处理的场景:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'id': [1,1,1,5,5,5,5],
    'speed': [1.2,1.9,1.0,0.9,1.3,3.5,0.4],
    'other_col': ['...']*7
})

threshold = 1.5

def filter_group(group):
    # 找到分组内首个speed超阈值的行索引
    first_over_idx = group[group['speed'] > threshold].index.min()
    if pd.notna(first_over_idx):
        # 返回该索引之前的所有行(不包含超阈值行)
        return group.loc[:first_over_idx - 1]
    else:
        # 若分组内无超阈值行,返回整个分组
        return group

result = df.groupby('id', group_keys=False).apply(filter_group)

print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:05:42