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

如何将Pandas中DatetimeIndex的小时级Series转换为日-小时透视表

解决方案

你的问题出在手动用unique()指定行和列标签时,没有建立原数据与这些标签的映射关系,导致Pandas无法正确填充数值。以下两种方法可以解决:

方法1:使用pivot函数

先将Series转换为带日期列的DataFrame,再通过pivot按日序和小时分组填充:

# 将Series转为带datetime列的DataFrame
temp_df = prices.reset_index(name='price')
# 按dayofyear和hour构建透视表
df = temp_df.pivot(
    index=temp_df['index'].dt.dayofyear,
    columns=temp_df['index'].dt.hour,
    values='price'
)
# 可选:重命名行/列索引的标签
df = df.rename_axis(index='dayofyear', columns='hour')

方法2:使用unstack(更简洁)

通过将原索引拆分为dayofyear和hour两级索引,再将小时层级转为列:

# 构建多级索引:第一级是dayofyear,第二级是hour
prices_multi = prices.set_axis(
    pd.MultiIndex.from_arrays(
        [prices.index.dayofyear, prices.index.hour],
        names=['dayofyear', 'hour']
    )
)
# 将hour层级展开为列
df = prices_multi.unstack(level='hour')

补充说明

  • 如果数据包含闰年的366天,可通过df = df[df.index != 366]过滤掉该行;
  • 最终生成的DataFrame会自动按1-365天、0-23小时排序,形状为365×24。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:47:40