Pandas筛选指定日期后novice race记录:排除前期有新手赛的车手
车手新手赛事记录筛选与分组查询方案
需求拆解
- 筛选2018年1月1日及以后的「novice race」记录
- 排除所有在2018年之前已有「novice race」记录的车手
- 对符合条件的车手,提取其所有赛事记录中按日期排序的前两场赛事类型组合
实现代码(基于Pandas)
1. 准备示例数据
import pandas as pd # 模拟赛事数据 data = { 'driver_id': [1, 1, 2, 2, 3, 3], 'race_date': ['2017-05-10', '2018-06-15', '2018-03-20', '2019-01-10', '2016-11-05', '2018-07-22'], 'race_type': ['novice', 'novice', 'novice', 'professional', 'novice', 'novice'] } df = pd.DataFrame(data) df['race_date'] = pd.to_datetime(df['race_date'])
2. 标记有前期新手赛事的车手
先找出所有在2018年前参加过novice race的车手ID:
# 提取2018年前有novice race的车手 pre_2018_novice_drivers = df[(df['race_date'] < '2018-01-01') & (df['race_type'] == 'novice')]['driver_id'].unique()
3. 筛选符合条件的车手数据
保留无前期新手赛事的车手所有记录,并按日期排序:
# 筛选目标车手的所有赛事记录 qualified_drivers = df[~df['driver_id'].isin(pre_2018_novice_drivers)] # 按车手ID和赛事日期排序,确保顺序正确 qualified_drivers_sorted = qualified_drivers.sort_values(by=['driver_id', 'race_date'])
4. 提取前两场赛事类型组合
按车手分组后取前两场记录,聚合为赛事类型组合:
# 分组取前两场,合并为类型组合 first_two_races = qualified_drivers_sorted.groupby('driver_id').head(2)\ .groupby('driver_id')['race_type']\ .apply(list)\ .reset_index(name='first_two_race_types')
输出结果
运行后得到的first_two_races仅包含符合要求的车手:
| driver_id | first_two_race_types |
|---|---|
| 2 | ['novice', 'professional'] |
内容的提问来源于stack exchange,提问作者Eoin Vaughan
相关产品推荐
相关产品推荐

