Pandas DatetimeIndex:频率字符串中的周期数? [英] Pandas DatetimeIndex: Number of periods in a frequency string?
问题描述
如何使用频率字符串(偏移别名)计算 Pandas DatetimeIndex 中的周期数?例如,假设我有以下 DatetimeIndex:
How can I get a count of the number of periods in a Pandas DatetimeIndex using a frequency string (offset alias)? For example, let's say I have the following DatetimeIndex:
idx = pd.date_range("2019-03-01", periods=10000, freq='5T')
我想知道一周有多少个 5 分钟的时间段,或7D".我可以手动"计算:
I would like to know how many 5 minute periods are in a week, or '7D'. I can calculate this "manually":
periods = (7*24*60)//5
或者我可以得到一个虚拟索引的长度:
Or I can get the length of a dummy index:
len(pd.timedelta_range(start='1 day', end='8 days', freq='5T'))
这两种方法似乎都不是很有效.有没有更好的方法使用 Pandas 日期功能?
Neither approach seems very efficient. Is there a better way using Pandas date functionality?
推荐答案
我终于想出了一个合理的解决方案:
I finally figured out a reasonable solution:
pd.to_timedelta('7D')//idx.freq
这样做的好处是我可以使用频率字符串(偏移别名)指定一个范围,并且可以从数据帧中推断出周期或频率.@Terry 建议的 numpy 解决方案仍然是速度很重要的最快解决方案.
This has the advantage that I can specify a range using a frequency string (offset alias) and the period or frequency is inferred from the dataframe. The numpy solution suggested by @Terry is still the fastest solution where speed is important.
这篇关于Pandas DatetimeIndex:频率字符串中的周期数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!