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

如何在指定日期范围内找出两个DataFrame的共同id_number

解决方法

步骤1:导入库并创建DataFrame

先导入pandas,将给定数据转换为DataFrame:

import pandas as pd

data1 = {'date':  ['5/09/22', '7/09/22', '7/09/22','10/09/22'],
            'second_column': ['first_value', 'second_value', 'third_value','fourth_value'],
             'id_number':['AA576bdk89', 'GG6jabkhd589', 'BXV6jabd589','BXzadzd589'],
            'fourth_column':['first_value', 'second_value', 'third_value','fourth_value'],}
    
data2 = {'date':  ['5/09/22', '7/09/22', '7/09/22', '7/09/22', '7/09/22', '11/09/22'],
            'second_column': ['first_value', 'second_value', 'third_value','fourth_value', 'fifth_value','sixth_value'],
             'id_number':['AA576bdk89', 'GG6jabkhd589', 'BXV6jabd589','BXV6mkjdd589','GGdbkz589', 'BXhshhsd589'],
            'fourth_column':['first_value', 'second_value', 'third_value','fourth_value', 'fifth_value','sixth_value'],}

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

步骤2:转换日期格式

原始日期是字符串,直接比较容易出错,先把date列转为datetime类型:

df1['date'] = pd.to_datetime(df1['date'], format='%d/%m/%y')
df2['date'] = pd.to_datetime(df2['date'], format='%d/%m/%y')

这里用%d/%m/%y是因为日期格式是日/月/年(比如5/09/22是2022年9月5日),如果你的日期格式是月/日/年,就改成%m/%d/%y。

步骤3:筛选符合条件的记录

先确定df1的日期范围,再筛选df2中日期在该范围内、且id_number存在于df1中的行:

# 获取df1的日期区间
min_date = df1['date'].min()
max_date = df1['date'].max()

# 筛选符合条件的df2行
filtered_df2 = df2[(df2['date'] >= min_date) & (df2['date'] <= max_date) & (df2['id_number'].isin(df1['id_number']))]

# 如果只需要去重后的id列表
matching_ids = filtered_df2['id_number'].unique().tolist()

结果说明

运行代码后:

  • filtered_df2包含df2中日期在5/09/22至10/09/22之间、且id存在于df1的所有行;
  • matching_ids是去重后的符合条件的id列表,结果为['AA576bdk89', 'GG6jabkhd589', 'BXV6jabd589']。

简化写法

也可以把代码合并为一步:

df1['date'] = pd.to_datetime(df1['date'], format='%d/%m/%y')
df2['date'] = pd.to_datetime(df2['date'], format='%d/%m/%y')

matching_ids = df2[
    (df2['date'].between(df1['date'].min(), df1['date'].max())) &
    (df2['id_number'].isin(df1['id_number']))
]['id_number'].unique().tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:55:19