You need to enable JavaScript to run this app. 使用interpolate为pandas时间序列DataFrame新增行实现半小时级温度插值
优惠活动
大模型
产品
解决方案
定价
更多

使用interpolate为pandas时间序列DataFrame新增行实现半小时级温度插值

问题原因

你已经将datetime列设为DataFrame的索引,该索引的类型为Timestamp时间戳类型,而你执行df.loc[-1,'tp'] = n+1时,第一个位置传的是整数-1,和索引要求的Timestamp类型不匹配,所以触发了类型错误。同时你通过循环逐行插入新数据的方式效率极低,针对时间序列升采样插值的场景,pandas自带的重采样功能可以更简洁地实现需求。

最优解决方案

直接对时间序列做半小时粒度重采样后插值,一行代码就能完成升采样+插值的操作,无需手动插入行:

import numpy as np
import pandas as pd

# 构造原始小时级数据
d1 = '2020-10-21'
d2 = '2020-10-22'
dt_index = pd.date_range(d1, periods=48, freq='H')
df = pd.DataFrame({
    'temp': 50 + 20 * np.sin(np.linspace(0, 0.91*np.pi, 48))
}, index=dt_index)

# 重采样为半小时粒度后做线性插值
df_30min = df.resample('30T').interpolate(method='linear')

# 计算交易时段:每天共48个时段,从1开始顺排
df_30min['tp'] = df_30min.index.hour * 2 + df_30min.index.minute//30 + 1

print(df_30min.head(10))

运行后你就能得到所有半小时时间点对应的插值温度和对应的交易时段编号,完全符合你的需求。

原代码修改方案

如果你坚持要按原逻辑手动插入行实现,只需要把datetime列作为普通列、不设置为索引即可:

import numpy as np
import pandas as pd
from datetime import datetime, date, timedelta

# my dataset
df = pd.DataFrame()
d1 = '2020-10-21'
d2 = '2020-10-22'
df['date'] = pd.to_datetime([d1]*24+[d2]*24, format='%Y-%m-%d')
df['time'] = pd.date_range(d1, periods=len(df), freq='H').time
df['temp'] = pd.DataFrame((50+20*np.sin(np.linspace(0,0.91*np.pi,len(df))))).values

# combine time and date
df.loc[:,'datetime'] = pd.to_datetime(df.date.astype(str)+' '+df.time.astype(str))
df = df.drop(['date','time'], axis=1)
# 注释掉设置datetime为索引的代码,避免索引类型不匹配
# df = df.set_index('datetime')

# trading period
df['tp'] = pd.DataFrame(df.datetime.dt.hour.values*2+1).values

# 插入偶数交易时段行
for n in df.tp.values:
    df.loc[len(df), 'tp'] = n+1
df = df.sort_values('tp').reset_index(drop=True)

# 插值填充空值
df = df.interpolate(method='linear')

print(df.head(10))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 20:45:02