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

Pandas中使用DatetimeIndex筛选时如何保留频率属性?

示例

我有一个年度频率的DatetimeIndex,以及两个序列,它们共同覆盖了该索引的所有值:

import pandas as pd
i = pd.date_range('2023', freq='AS', periods=3)
s1 = pd.Series([1,2], [i[0], i[2]])
s2 = pd.Series([-30], [i[1]])

concat = pd.concat([s1, s2])

最后一行我将这些序列合并为一个更长的序列,其索引值未排序。

我可以使用result = concat.loc[i]按原索引顺序筛选值。

问题

问题在于freq属性丢失了。

原索引的频率为i.freq(<YearBegin: month=1>),但result.index.freq的值为None。

我对此感到困惑;我理解.loc[]会筛选concat中的对应值,并返回以i为索引的Series,所以我认为result的索引应该保留频率。

有没有办法保留该频率?

说明
  • 在这里,我可以手动设置频率,比如result.index.freq = 'AS',或者让pandas推断频率:result.index.freq = pd.infer_freq(result.index)。
  • 但我无法保证i始终是DatetimeIndex。
  • 我希望避免进行大量的类型检查和错误捕获,比如:
    if isinstance(concat.index, pd.DatetimeIndex) and i.freq:
      try:
        concat.index.freq = i.freq
      except ValueError:
        pass
    
    ……如果有可能的话。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:52:36