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

如何为Pandas DataFrame设置1秒时间窗口并以250毫秒步长滑动

How to Create Rolling 1-Second Window Slices with 250ms Step in Pandas

Got it, let's break down how to build that array of DataFrame slices you need. The goal is to slide a 1-second window over your time-series data, moving 250ms each step, and capture each window as a separate DataFrame fragment. Here's a step-by-step solution:

Step 1: Prepare Your Time Column

First, make sure your time column is properly parsed as a datetime type—this is critical for accurate time-based windowing:

import pandas as pd

# Sample data (replace with your actual DataFrame)
data = [
    ["2018-01-24 13:43:58.700", 0.021973, 0.012283, -0.995468, 1],
    ["2018-01-24 13:43:58.711", 0.021072, 0.013779, -0.994308, 1],
    ["2018-01-24 13:43:58.721", 0.020157, 0.015717, -0.995575, 1],
    ["2018-01-24 13:43:58.733", 0.017883, 0.012756, -0.993927, 1],
    ["2018-01-24 13:43:59.700", 0.021194, 0.012161, -0.994873, 1]
]
df = pd.DataFrame(data, columns=["time", "ax", "ay", "az", "id"])

# Convert time column to datetime
df["time"] = pd.to_datetime(df["time"])

Step 2: Generate Window Start Times

We need to create a sequence of start times for each window. The first start time is the earliest timestamp in your data, and we increment by 250ms until we reach a start time that's at least 1 second before the latest timestamp (so the final window can fully cover 1 second):

# Calculate all valid window start times
start_times = pd.date_range(
    start=df["time"].min(),
    end=df["time"].max() - pd.Timedelta(seconds=1),
    freq="250ms"
)

Step 3: Extract Each Window Slice

Loop through each start time, define the corresponding end time (start + 1 second), and filter the original DataFrame to get the rows within that time range. Store each slice in an array:

window_slices = []

for start in start_times:
    end = start + pd.Timedelta(seconds=1)
    # Filter rows where time is >= start and < end
    current_slice = df[(df["time"] >= start) & (df["time"] < end)].copy()
    window_slices.append(current_slice)

Step 4: Verify the Result

You can check the slices to confirm they match your requirements. For example, print the first slice's time range:

print("First window time range:", window_slices[0]["time"].min(), "to", window_slices[0]["time"].max())
print("Number of slices created:", len(window_slices))

Notes for Edge Cases

  • If your data has multiple id groups, you can wrap this logic in a groupby to process each ID separately:
    grouped_slices = {}
    for id_val, group in df.groupby("id"):
        id_start_times = pd.date_range(
            start=group["time"].min(),
            end=group["time"].max() - pd.Timedelta(seconds=1),
            freq="250ms"
        )
        id_slices = []
        for start in id_start_times:
            end = start + pd.Timedelta(seconds=1)
            id_slices.append(group[(group["time"] >= start) & (group["time"] < end)].copy())
        grouped_slices[id_val] = id_slices
    
  • This approach ensures each window is a full 1-second span, and we only create windows where there's enough data to cover the entire 1-second period.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:39:08