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

如何在Pandas DataFrame中实现date:value字典的日期范围值映射

问题原因

你的代码全返回NaN的核心原因是类型不匹配:DataFrame的索引是datetime64时间类型,而你传入的字典key是字符串类型,map操作无法匹配到对应值,后续ffill自然也没有有效值可以填充。

解决方法

先将字典转换为时间索引的Series,再通过reindex对齐原DataFrame的索引并向前填充即可,完整代码如下:

import pandas as pd

df = pd.DataFrame(range(19), index=pd.date_range(start="2010-01-01", end="2010-01-10", freq="12H"))
dct = {
    "2009-01-01": 1,
    "2010-01-05": 2,
    "2020-01-01": 3,
}

# 将字典转为时间索引的Series
map_series = pd.Series(dct.values(), index=pd.to_datetime(dct.keys()))
# 对齐df索引,向前填充
df["test"] = map_series.reindex(df.index, method="ffill")

执行后输出完全符合预期:

  • 2010-01-01 ~ 2010-01-04 所有时段的test值为1
  • 2010-01-05 ~ 2010-01-10 所有时段的test值为2
  • 字典中2020年的配置不在目标时间范围内,不会生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:24:05