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

编写函数时如何从已重采样的Series中获取重采样规则?

获取Pandas重采样后Series的采样规则

嘿,我刚好碰到过类似的需求,要从已经重采样完成的Pandas Series里提取它的采样规则,比如你提到的返回'6H'这种格式。下面是我验证过的解决方案:

核心思路

重采样后的Series索引一般是DatetimeIndex,我们可以通过两种方式获取采样规则:

  1. 直接读取索引的freq属性(最直接,优先用这个)
  2. 如果freq属性丢失,计算索引相邻时间差的众数来推导采样规则

实现代码

import pandas as pd

def get_resample_rule(resampled_series):
    # 先校验输入的Series索引是否为DatetimeIndex(重采样结果的标准索引类型)
    if not isinstance(resampled_series.index, pd.DatetimeIndex):
        raise ValueError("输入的Series必须是重采样后的结果,即索引为DatetimeIndex")
    
    # 尝试直接读取索引的freq属性
    index_freq = resampled_series.index.freq
    if index_freq is not None:
        return index_freq.freqstr
    
    # 若freq属性丢失,通过计算相邻时间差的众数来推导
    time_diffs = resampled_series.index.to_series().diff().dropna()
    most_common_diff = time_diffs.value_counts().idxmax()
    return most_common_diff.freqstr

示例测试

比如构造一个按6小时重采样的Series:

# 创建6小时间隔的索引
idx = pd.date_range(start='2011-01-01', periods=5, freq='6H')
# 生成测试Series
test_series = pd.Series([1,2,3,4,5], index=idx)

# 调用函数获取采样规则
print(get_resample_rule(test_series))  # 输出: '6H'

如果你的Series索引的freq属性因为某些操作丢失了(比如手动修改过索引),这个函数也能通过计算时间差的方式正确返回采样规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:02:01