Python:按id分组后筛选DataFrame中speed超阈值行之前的所有行
Pandas按分组筛选首个超阈值行之前的所有数据
需求描述
给定一个包含多特征的DataFrame,需按id字段分组:
- 对每个分组,识别
speed字段值首次超过阈值(示例中阈值设为1.5)的行 - 筛选并保留该行之前的所有行
输入示例
| id | speed | ... |
|---|---|---|
| 1 | 1.2 | ... |
| 1 | 1.9 | ... |
| 1 | 1.0 | ... |
| 5 | 0.9 | ... |
| 5 | 1.3 | ... |
| 5 | 3.5 | ... |
| 5 | 0.4 | ... |
期望输出
| id | speed | ... |
|---|---|---|
| 1 | 1.2 | ... |
| 5 | 0.9 | ... |
| 5 | 1.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
相关产品推荐
相关产品推荐

