【问题标题】:Python: Is there a function to find the last week of a month? [closed]Python:是否有查找一个月最后一周的函数? [关闭]
【发布时间】:2022-12-09 13:44:27
【问题描述】:

我想重新采样以获得该月最后一周的所有值。但是,有几个星期在 2 个月之间重叠。对于 Python,如果我使用以下代码,它会忽略这些星期:

m0_2 = q0.resample('M').last()

例如,对于一月,代码将“27-Jan-89”作为该月的最后一周。但实际上,“89 年 2 月 3 日”这一周也有 Jan 的日子,所以我想要值 2。

谢谢

初始测向:

89 年 1 月 20 日 3
89 年 1 月 27 日 4
89 年 2 月 3 日 2
89 年 2 月 10 日 5
89 年 2 月 17 日 3
24-Feb-89 5
89 年 3 月 3 日 5
89 年 3 月 10 日 6
89 年 3 月 17 日 4
89 年 3 月 24 日 5
89 年 3 月 31 日 7
89 年 4 月 7 日 6
89 年 4 月 14 日 6
89 年 4 月 21 日 4
89 年 4 月 28 日 7
89 年 5 月 5 日 5
89 年 5 月 12 日 6
89 年 5 月 19 日 5
89 年 5 月 26 日 7
89 年 6 月 2 日 7

上面代码的输出

1989-01-31 4
1989-02-28 5
1989-03-31 7
1989-04-30 7
1989-05-31 7
1989-06-30 7

期望的输出

                  Jan   Feb   Mar   Apr   May
                 1989  1989  1989  1989  1989
                 
                 2.00  5.00  7.00  5.00  7.00

【问题讨论】:

  • 这似乎是通过按月和年键控的itertools.groupby 流式传输数据来处理的最佳方式;您将获得包含该月所有周的每月迭代器。
  • @ShadowRanger:感谢您的回复。你能显示代码吗?

标签: python resampling


【解决方案1】:

检查日期是否在一个月的最后一周并进行操作。

import pandas as pd

data = pd.DataFrame(data={
    'dates':['2022-11-27', '2022-11-28', '2022-12-03', '2022-12-04', '2023-01-30'],
})
data['dates'] = pd.to_datetime(data['dates'])

# consider week starts from Monday
from calendar import monthrange

for _, row in data.iterrows():
    weekday, max_days = monthrange(row['dates'].year, row['dates'].month)
    no_of_weeks_in_month = (max_days + weekday - 1) // 7  # add 1 if you want week number to index from 1
    offset_week = (row['dates'].day + weekday -1) // 7 

    if offset_week == no_of_weeks_in_month:
        # Grab to your monthly data
        pass
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    相关资源
    最近更新 更多