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

Python如何对pandas DataFrame按指定时间戳提取对应秒内全部行

解决方法

你的需求是为每个指定时间点独立生成其往前推0.9秒到该时间点的0.1秒间隔时间序列,仅原时间点保留对应Label,其余位置为空,不同时间点的序列互不干扰。可以用以下两种方式实现:

方式1:循环实现(逻辑直观,适合小数据量)

import pandas as pd

# 你的原始数据
df = pd.DataFrame({      
    'Time' : ['2021-03-20 09:27:28.400','2021-03-20 09:29:15.200','2021-03-20 09:30:38.200'],
    'Label' : ['A','B','A'],   
   })
df['Time'] = pd.to_datetime(df['Time'])

res_list = []
for _, row in df.iterrows():
    # 生成当前时间点对应1秒区间的时间序列(步长0.1秒)
    time_seq = pd.date_range(
        start=row["Time"] - pd.Timedelta("0.9s"),
        end=row["Time"],
        freq="0.1S"
    )
    # 构造临时表,仅最后一行赋值原始Label
    temp = pd.DataFrame({"Time": time_seq, "Label": pd.NA})
    temp.iloc[-1, temp.columns.get_loc("Label")] = row["Label"]
    res_list.append(temp)

# 拼接所有区间结果
df_out = pd.concat(res_list, ignore_index=True)

方式2:向量化实现(无循环,适合大数据量)

import pandas as pd

df = pd.DataFrame({      
    'Time' : ['2021-03-20 09:27:28.400','2021-03-20 09:29:15.200','2021-03-20 09:30:38.200'],
    'Label' : ['A','B','A'],   
   })
df['Time'] = pd.to_datetime(df['Time'])

# 为每行生成对应时间序列后展开
df["time_seq"] = df.apply(
    lambda x: pd.date_range(x["Time"] - pd.Timedelta("0.9s"), x["Time"], freq="0.1S"), 
    axis=1
)
df = df.explode("time_seq", ignore_index=True)
# 仅原时间点保留Label,其余置空
df["Label"] = df["Label"].where(df["time_seq"] == df["Time"], pd.NA)
df_out = df[["time_seq", "Label"]].rename(columns={"time_seq": "Time"})

两种方式输出的结果和你给出的预期格式完全一致,你给出的预期结果里2021-03-20 09:29:14.000属于笔误,实际生成的会是正确的2021-03-20 09:29:15.000。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:24:06