【问题标题】:Pandas Approximate Frequency Per Year of a DateTimeIndexPandas DateTimeIndex 每年的近似频率
【发布时间】:2021-02-08 17:56:27
【问题描述】:

我在不同的文件中有多个时间序列,我知道 Pandas 可以推断每个时间序列的频率:

pd.infer_freq(data.index)

是否有一种编程方式可以从一般文件中获取每年的大致频率。例如:

'M' -> 12
'BM' -> 12
'B' -> 252
'D' -> 365

【问题讨论】:

  • stackoverflow.com/questions/54945550/… 很接近,但我不确定如何调整答案。
  • 虽然这是一个很酷的问题,但考虑到常见频率的数量非常少,实际上可能更容易自己计算它们并将它们存储在某些脚本中的字典中。我提出的解决方案有点矫枉过正,也许并不总是给你你想要的数字,但如果你想在 pd.bdate_range 中包含一个 calendar 以排除假期,你应该能够修改它以获得号码

标签: python pandas frequency datetimeindex


【解决方案1】:

这是另一种选择。我们将使用提供的频率创建一个 date_range,然后使用 groupby 来找出适合一年的最常见数字。 periods 参数应该足够大,以便给定日期范围创建多年数据的频率。真的不需要更改它,除非您想要ns 或非常小的东西。 (但对于那些手动计算会更有效)。

def infer_periods_in_year(freq, periods=10**4):
    """
    freq : str pandas frequency alias.
    periods : numeric, given freq, should create many years. 
    """
    
    while True:
        try:
            s = pd.Series(data=pd.date_range('1970-01-01', freq=freq, periods=periods))
            break
        # If periods is too large
        except (pd.errors.OutOfBoundsDatetime, OverflowError, ValueError): 
            periods = periods/10
    
    return s.groupby(s.dt.year).size().value_counts().index[0]

infer_periods_in_year('D')
#365
infer_periods_in_year('BM')
#12
infer_periods_in_year('M')
#12
infer_periods_in_year('B')
#261
infer_periods_in_year('W')
#52
infer_periods_in_year('min', periods=10**7)
#525600

【讨论】:

    猜你喜欢
    • 2019-10-08
    • 2021-12-26
    • 2019-07-23
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2020-06-22
    相关资源
    最近更新 更多