如何统计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的结果如下:
| Name | Dates | Total Weeks | Total Periods | Long Periods (≥2 weeks) |
|---|---|---|---|---|
| a | ['8/5/2021'] | 1 | 1 | 0 |
| b | ['12/21/2021', '12/28/2021'] | 2 | 1 | 1 |
| c | ['8/10/2021', '8/27/2021', '9/3/2021', '9/10/2021', '9/17/2021'] | 5 | 2 | 1 |
| d | ['8/23/2021', '9/23/2021', '10/23/2021'] | 3 | 3 | 0 |
| e | ['8/10/2021', '9/27/2021', '10/3/2021', '11/10/2021', '11/17/2021', '12/27/2021'] | 6 | 5 | 1 |
结果说明
- Total Periods:统计所有连续/单周时段数,单周算1个,连续N周算1个
- Long Periods (≥2 weeks):仅统计长度≥2周的连续时段数
内容的提问来源于stack exchange,提问作者Serena
相关产品推荐
相关产品推荐

