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

如何将pandas DataFrame按指定重叠占比分割为滑动窗口并保留日期信息

实现带指定重叠占比的pandas时序滑动窗口分割

实现方案

pandas 1.3及以上版本内置的rolling方法已经支持step步长参数,可以直接满足需求,无需自行编写分组逻辑。

前置准备

先确保原DataFrame满足两个条件:

  • Date列已转换为datetime类型
  • 数据已按Date列升序排序

代码实现

import pandas as pd

# 预处理原数据
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date').reset_index(drop=True)

# 自定义参数
window_size = 4 # 窗口大小n
overlap_ratio = 75 # 重叠占比o%
step = int(window_size * (1 - overlap_ratio / 100)) # 计算滑动步长

# 生成滑动窗口结果
result_list = []
for win in df.rolling(window=window_size, step=step):
    # 仅保留长度符合要求的完整窗口,如需保留尾部不完整窗口可删除该判断
    if len(win) == window_size:
        result_list.append({
            "date_start": win["Date"].iloc[0],
            "date_end": win["Date"].iloc[-1],
            "power": win["Power"].tolist()
        })

# 转换为结果DataFrame
result_df = pd.DataFrame(result_list)

低版本pandas兼容方案

如果使用的pandas版本低于1.3,没有step参数,可直接用索引切片实现,逻辑更通用:

window_size = 4
overlap_ratio = 75
step = int(window_size * (1 - overlap_ratio / 100))
max_start_idx = len(df) - window_size + 1

result_list = []
for i in range(0, max_start_idx, step):
    win = df.iloc[i:i+window_size]
    result_list.append({
        "date_start": win["Date"].iloc[0],
        "date_end": win["Date"].iloc[-1],
        "power": win["Power"].tolist()
    })

result_df = pd.DataFrame(result_list)

两种方案输出结果都和你给出的预期格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:54:02