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

为何用日期字符串索引DataFrame会影响列返回类型?

整数列返回浮点型的原因解析

你遇到的这个现象,核心原因在于DataFrame的索引类型和Pandas的索引匹配机制:

  • 你的DataFrame索引是object类型(存储的是datetime.datetime对象),而非Pandas专门的DatetimeIndex类型。
  • 当用字符串"20200101"索引时,Pandas需要先把字符串解析为日期,再去匹配索引中的datetime对象。这个过程中,为了兼容可能出现的缺失值场景,Pandas会自动将结果转换为浮点型(numpy.float64)——哪怕当前数据里没有缺失值。
  • 当用datetime.datetime(2020,1,1)直接索引时,属于精确的标签匹配,Pandas可以直接返回列的原生整数类型(numpy.int64)。

验证与解决方法

如果把索引转换成DatetimeIndex,两种索引方式都会返回整数:

df.index = pd.DatetimeIndex(df.index)
df.loc['20200101', 'c']  # 返回int
df.loc[datetime.datetime(2020,1,1), 'c']  # 返回int

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:15:35