How to efficiently find the date of the N-th occurrence of a specific weekday in each month within a given pandas DataFrame date range?

huangapple go评论66阅读模式
英文:

How to efficiently find the date of the N-th occurrence of a specific weekday in each month within a given pandas DataFrame date range?

问题

我有一个带有日期范围的pandas DataFrame,并且我想找到该范围内每个月的特定星期几(例如,第三个星期二)的日期。我处理的数据集跨越了几年,因此效率非常重要。这是我的DataFrame的外观:

import pandas as pd

date_rng = pd.date_range(start='1/1/2020', end='12/31/2023', freq='D')
df = pd.DataFrame(date_rng, columns=['date'])

不确定这是否属于SO问题范畴,但我想要比遍历所有日期更快的方法。是否有更高效/专业的方法来实现这个目标?

英文:

I have a pandas DataFrame with a date range, and I want to find the date of the N-th occurrence of a specific weekday (say, the third Tuesday) of each month within that range. I'm dealing with a large dataset spanning several years, so efficiency is crucial. Here's how my DataFrame looks:

import pandas as pd

date_rng = pd.date_range(start='1/1/2020', end='12/31/2023', freq='D')
df = pd.DataFrame(date_rng, columns=['date'])

IDK if this fall under the umbrella of SO questions, bud i'd like a faster approach than just looping through everything. Is there a more efficient/pro way of doing this?

答案1

得分: 2

如评论中@richard建议的,您应该在date_range中使用WOM-3TUE频率。有关频率的更多详细信息,请参阅此页面(尽管此频率没有明确记录)。

import pandas as pd
date_rng = pd.date_range(start='1/1/2020', end='12/31/2023', freq='WOM-3TUE')
df = pd.DataFrame(date_rng, columns=['date'])

输出:

         date
0  2020-01-21
1  2020-02-18
2  2020-03-17
3  2020-04-21
4  2020-05-19
          ...
43 2023-08-15
44 2023-09-19
45 2023-10-17
46 2023-11-21
47 2023-12-19
英文:

As suggested by @richard in the comments, you should use the WOM-3TUE frequency in date_range. See this page for more details on the frequencies (although this one is not clearly documented).

import pandas as pd
date_rng = pd.date_range(start='1/1/2020', end='12/31/2023', freq='WOM-3TUE')
df = pd.DataFrame(date_rng, columns=['date'])

Output:

         date
0  2020-01-21
1  2020-02-18
2  2020-03-17
3  2020-04-21
4  2020-05-19
          ...
43 2023-08-15
44 2023-09-19
45 2023-10-17
46 2023-11-21
47 2023-12-19

huangapple
  • 本文由 发表于 2023年6月16日 02:47:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定