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

如何统计DataFrame日期列表中的连续周时段数?

解决方案

我们可以通过自定义函数处理每个日期列表,结合日期转换和间隔判断来统计所需的时段数,具体步骤如下:

1. 导入依赖库

import pandas as pd
from datetime import datetime

2. 定义统计函数

这个函数接收日期字符串列表,完成日期转换、排序、间隔计算,最终返回两个统计结果:总连续时段数、长度≥2周的时段数。

def count_time_periods(dates_str_list):
    # 将字符串日期转为datetime对象并排序
    sorted_dates = sorted([datetime.strptime(date, '%m/%d/%Y') for date in dates_str_list])
    total_dates = len(sorted_dates)
    
    if total_dates == 0:
        return (0, 0)
    
    # 计算相邻日期的天数间隔
    day_gaps = [(sorted_dates[i] - sorted_dates[i-1]).days for i in range(1, total_dates)]
    
    total_periods = 1
    current_period_length = 1
    long_periods_count = 0
    
    for gap in day_gaps:
        if gap == 7:
            # 间隔7天,属于同一连续时段,长度加1
            current_period_length += 1
        else:
            # 间隔非7天,结束当前时段,检查是否为长时段
            if current_period_length >= 2:
                long_periods_count += 1
            total_periods += 1
            current_period_length = 1
    
    # 循环结束后检查最后一个时段
    if current_period_length >= 2:
        long_periods_count += 1
    
    return (total_periods, long_periods_count)

3. 应用函数到DataFrame

将函数应用到Dates列,生成两个新列:

# 初始化原始数据
data = [['a', ['8/5/2021'], 1], ['b', ['12/21/2021', '12/28/2021'], 2], ['c', ['8/10/2021',  '8/27/2021', '9/3/2021', '9/10/2021', '9/17/2021'], 5], ['d', ['8/23/2021', '9/23/2021', '10/23/2021'], 3], ['e', ['8/10/2021',  '9/27/2021', '10/3/2021', '11/10/2021', '11/17/2021', '12/27/2021'], 6]]
df = pd.DataFrame(data, columns=['Name', 'Dates', 'Total Weeks'])

# 生成新列
df[['Total Periods', 'Long Periods (≥2 weeks)']] = df['Dates'].apply(lambda x: pd.Series(count_time_periods(x)))

4. 最终结果

执行后,DataFrame的结果如下:

NameDatesTotal WeeksTotal PeriodsLong Periods (≥2 weeks)
a['8/5/2021']110
b['12/21/2021', '12/28/2021']211
c['8/10/2021', '8/27/2021', '9/3/2021', '9/10/2021', '9/17/2021']521
d['8/23/2021', '9/23/2021', '10/23/2021']330
e['8/10/2021', '9/27/2021', '10/3/2021', '11/10/2021', '11/17/2021', '12/27/2021']651

结果说明

  • Total Periods:统计所有连续/单周时段数,单周算1个,连续N周算1个
  • Long Periods (≥2 weeks):仅统计长度≥2周的连续时段数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:01:35