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

如何使用Pandas将并列时序宽格式DataFrame重塑为长格式

Pandas DataFrame 横向并排分组列转纵向拼接方案

你的原始DataFrame将两组「时间列+数值列」横向并排存储,只需拆分列组后纵向拼接、重置索引即可得到目标结构。

  • 方法1:numpy 高性能实现(代码最简洁)
import numpy as np
import pandas as pd

reshaped_sample_df = pd.DataFrame(
    np.vstack([sample_df.iloc[:, :2].values, sample_df.iloc[:, 2:].values])
)
  • 方法2:纯Pandas 原生实现(无numpy依赖)
# 拆分两组列,统一列名后纵向拼接并重置索引
part1 = sample_df[[0, 1]]
part2 = sample_df[[2, 3]].rename(columns={2:0, 3:1})
reshaped_sample_df = pd.concat([part1, part2], ignore_index=True)

执行上述任意一段代码,即可得到完全匹配预期的结果:

0       1
0  2011-01-01 00:00:00  123.39
1  2011-01-01 01:00:00  123.39
2  2011-01-01 02:00:00   123.4
3  2011-01-01 03:00:00   123.4
4  2011-01-01 04:00:00  123.41
5  2012-01-01 00:00:00   123.4
6  2012-01-01 01:00:00  123.38
7  2012-01-01 02:00:00   123.4
8  2012-01-01 03:00:00   123.4
9  2012-01-01 04:00:00   123.4

扩展提示:如果存在更多组横向并排的「时间+值」列对,只需按相同规则拆分列块,依次加入拼接列表即可批量完成转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:03:19