gpt4 book ai didi

python - 日期时间索引 : what is the purpose of 'freq' attribute?

转载 作者:行者123 更新时间:2023-12-01 02:18:08 25 4
gpt4 key购买 nike

我错过了 pandas DatatimeIndex 对象中“freq”属性的要点。它可以在构造时传递或随时设置为属性,但当此属性更改时,我没有看到 DatatimeIndex 对象的行为有任何差异。

请看这个例子。我们向 freq='B' 的 DatetimeIndex 添加 1 天,但返回的索引包含非工作日:

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

rng = pd.date_range('2012-01-05', '2012-01-10', freq=BDay())
index = pd.DatetimeIndex(rng)
print(index)

index2 = index + pd.Timedelta('1D')
print(index2)

这是输出:

DatetimeIndex(['2012-01-05', '2012-01-06', '2012-01-09', '2012-01-10'], dtype='datetime64[ns]', freq='B')

DatetimeIndex(['2012-01-06', '2012-01-07', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B')
  • 为什么在对 DatetimeIndex 执行计算 (+/- Timedelta) 时不考虑频率?
  • 为什么 freq 不反射(reflect) DatetimeIndex 中包含的实际数据? (即使包含非工作日,它也会显示“B”)

最佳答案

您正在寻找shift

index.shift(1)
Out[336]: DatetimeIndex(['2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B')

BDay 也会这样做

from pandas.tseries.offsets import BDay
index + BDay(1)
Out[340]: DatetimeIndex(['2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B')

关于python - 日期时间索引 : what is the purpose of 'freq' attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48192168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com