如何删除df1中与同participant的df2日期差超出±5天的行
实现方案
首先要先把两个DataFrame的createdOn字段统一转换为pandas的datetime类型,再按participant匹配判断时间差是否符合要求。
步骤1:预处理时间字段
import pandas as pd # 转换为datetime格式,确保时间计算准确 df1['createdOn'] = pd.to_datetime(df1['createdOn']) df2['createdOn'] = pd.to_datetime(df2['createdOn'])
步骤2:过滤符合要求的行
方法1:分组匹配(适合小数据量,写法简单)
先将df2按participant分组,再逐个判断df1每行是否存在符合时间差要求的匹配项:
def check_valid(row, df2_groups): # 当前participant在df2中无数据直接返回False if row['participant'] not in df2_groups.groups: return False # 取同participant的所有df2时间,判断是否存在±5天内的记录 df2_dates = df2_groups.get_group(row['participant'])['createdOn'] return (abs(df2_dates - row['createdOn']).dt.days <= 5).any() df2_groups = df2.groupby('participant') # 过滤得到结果 df1_result = df1[df1.apply(check_valid, axis=1, df2_groups=df2_groups)]
方法2:合并后去重(适合大数据量,性能更高)
通过按participant合并两个表,计算时间差后筛选有效记录:
# 保留df1原始索引用于后续筛选 df1 = df1.reset_index() # 仅合并需要用到的字段,减少内存占用 merged_df = df1.merge(df2[['participant', 'createdOn']], on='participant', suffixes=('_df1', '_df2')) # 计算时间差绝对值 merged_df['diff_days'] = abs(merged_df['createdOn_df1'] - merged_df['createdOn_df2']).dt.days # 提取符合条件的df1行索引 valid_indexes = merged_df[merged_df['diff_days'] <= 5]['index'].unique() # 得到最终结果 df1_result = df1[df1['index'].isin(valid_indexes)].drop('index', axis=1)
输出结果
两种方法得到的最终结果一致,都会删除df1中participant为2的行:
| participant | createdOn | id_sample | med |
|---|---|---|---|
| 1 | 2020-04-09 19:11:49 | 20 | True |
| 1 | 2020-04-09 19:12:36 | 21 | True |
| 1 | 2020-04-09 19:13:12 | 22 | True |
| 3 | 2020-04-09 19:21:16 | 24 | False |
内容的提问来源于stack exchange,提问作者luftgekuhltlover
相关产品推荐
相关产品推荐

