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

如何为Pandas时间序列手动指定自定义频率属性?

问题:为Pandas Series的索引手动设置自定义频率(freq='C', weekmask='1001000')

我有一个Pandas Series对象y,它的索引如下:

Index(['2020-01-03', '2020-01-07', '2020-01-10', '2020-01-14', '2020-01-17',
       ...
       '2023-07-25', '2023-07-28', '2023-08-01', '2023-08-04', '2023-08-08'],
      dtype='object', name='Date', length=376)

可以看到Pandas无法自动推断该索引的频率,y.index对象仅包含dtype、name和length属性,没有freq属性。

核心需求

如何为这个序列的索引强制设置freq='C'(自定义工作日频率)并指定weekmask='1001000',使得调用y.index.freq时能返回对应的频率对象?

已尝试的代码及问题

最初创建序列的函数:

def ensureSeriesHasAttributes(y: object, series_name: str) -> pd.Series:
    if not isinstance(y, pd.Series):
        y = pd.Series(y, name=series_name)
    else:
        y.name = series_name
    return y

修改为以下代码时触发了AssertionError:

def ensureSeriesHasAttributes(y: object, series_name: str) -> pd.Series:
    if not isinstance(y, pd.Series):
        y = pd.Series(y, name=series_name, freq='C', weekmask='1001000')
    else:
        y.name = series_name
        y.index.freq = 'C'
        y.index.weekmask = '1001000'
    return y

正确实现方式

直接给index.freq赋值字符串无效,需要创建CustomBusinessDay实例并赋值,同时要先将索引转换为DatetimeIndex类型:

import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay

def ensureSeriesHasAttributes(y: object, series_name: str) -> pd.Series:
    if not isinstance(y, pd.Series):
        y = pd.Series(y, name=series_name)
    else:
        y.name = series_name
    
    # 1. 将object类型索引转换为DatetimeIndex
    y.index = pd.to_datetime(y.index, name='Date')
    # 2. 创建自定义工作日频率对象
    custom_freq = CustomBusinessDay(weekmask='1001000')
    # 3. 为索引绑定频率属性
    y.index.freq = custom_freq
    
    return y

关键说明

  • 原始索引是object类型,必须先转换为DatetimeIndex才能设置频率属性
  • 不能直接赋值字符串'C'给index.freq,需实例化CustomBusinessDay并传入weekmask参数
  • weekmask='1001000'表示每周周一、周四为工作日(字符位置对应周一到周日,1代表工作日,0代表休息日)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:26:14