英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论