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

如何重新采样半时间序列半整数索引的DataFrame并延续时间序列?

问题:如何将混合索引的DataFrame转换为连续时间序列的单一列?

原始DataFrame如下:

close         0
2020-01-02 09:00:00+00:00  0.467291       NaN
2020-01-02 09:30:00+00:00  0.467267       NaN
2020-01-02 10:00:00+00:00  0.467729       NaN
2020-01-02 10:30:00+00:00  0.467923       NaN
2020-01-02 11:00:00+00:00  0.466707       NaN
...                             ...       ...
1500                            NaN  0.140868
1501                            NaN  0.136557
1502                            NaN  0.131828
1503                            NaN  0.128827
1504                            NaN  0.128978

该DataFrame特征:

  • 索引前半部分为时间序列,后半部分为整数
  • close列前半段有数值、后半段为NaN,0列则相反

需求:能否通过向前填充延续时间序列,同时将0列内容填充到close列,得到如下仅含close列的连续时间序列索引结果?

close        
2020-01-02 09:00:00+00:00  0.467291       
2020-01-02 09:30:00+00:00  0.467267       
2020-01-02 10:00:00+00:00  0.467729       
2020-01-02 10:30:00+00:00  0.467923       
2020-01-02 11:00:00+00:00  0.466707       
...                             ...       
2020-02-17 09:30:00+00:00  0.161267       
2020-02-17 10:00:00+00:00  0.165729       
2020-02-17 10:30:00+00:00  0.164923       
2020-02-17 11:00:00+00:00  0.163707       

解决方案

可以实现,具体步骤及代码如下:

步骤说明

  1. 提取原始时间序列部分的索引,自动识别时间间隔(如30分钟)
  2. 生成与原DataFrame行数一致的连续时间序列索引
  3. 将0列的非空值填充到close列的NaN位置
  4. 替换原混合索引为新生成的连续时间索引,保留close列

代码实现

import pandas as pd

# 假设原始DataFrame名为df
# 1. 筛选出时间类型的索引,推断时间频率
time_index = df.index[df.index.map(lambda x: isinstance(x, pd.Timestamp))]
time_freq = pd.infer_freq(time_index)
# 若自动推断失败,可手动指定频率,比如30分钟:time_freq = '30T'

# 2. 生成完整的连续时间序列索引
full_time_index = pd.date_range(start=time_index[0], periods=len(df), freq=time_freq)

# 3. 将0列的值填充到close列的空值位置
df['close'] = df['close'].fillna(df['0'])

# 4. 替换索引并整理结果
result_df = df[['close']].set_index(full_time_index)

# 查看结果
print(result_df)

关键细节

  • pd.infer_freq可自动识别时间序列的间隔,适配不同的时间粒度
  • fillna方法直接完成横向填充,无需复杂的循环操作
  • 生成的连续时间索引长度与原DataFrame一致,保证数据一一对应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:16:05