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

如何重复DataFrame并递增时间戳?求有效解决方案

解决方案

你的需求是重复原DataFrame并让time[s]列连续递增,原代码的问题在于groupby(level=0)——执行ignore_index=True后原索引已被重置,这个分组逻辑不成立。

以下是两种可行的实现方式:

方法一:基于原时间范围计算偏移

适合原时间列不是从0开始或非连续的场景:

import pandas as pd

# 初始化原DataFrame
df = pd.DataFrame({'Temp': [20, 21, 21.5], 'time[s]': [0, 1, 2]})

repeat_count = 2
# 重复DataFrame并重置索引
df2 = pd.concat([df] * repeat_count, ignore_index=True)

# 计算每个重复块的时间偏移量
block_len = len(df)
time_step = df['time[s]'].max() + 1
df2['time[s]'] = df2['time[s]'] + (df2.index // block_len) * time_step

方法二:直接生成连续序列

如果时间本来就是从0开始的连续整数,这种方式更简洁:

import pandas as pd

df = pd.DataFrame({'Temp': [20, 21, 21.5], 'time[s]': [0, 1, 2]})

repeat_count = 2
df2 = pd.concat([df] * repeat_count, ignore_index=True)
# 直接生成从0开始的连续整数序列
df2['time[s]'] = range(len(df2))

两种方法执行后都能得到目标输出:

Temp  time[s]
0  20.0        0
1  21.0        1
2  21.5        2
3  20.0        3
4  21.0        4
5  21.5        5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:33:19