【问题标题】:Last week of the year is given attributed to the next year一年中的最后一周归因于下一年
【发布时间】:2022-01-05 12:36:08
【问题描述】:

2021 年的最后一周在 pandas.date_range() 函数中指定为 2022,而除周六和周日(1 月 1 日和 2 日)外,其余日子都属于 2021 年。

import pandas as pd

for x in pd.date_range(start='2021-12-01', end='2022-01-04', freq='W'):
    print('date: ', x, '\tweek: ', x.week, '\tyear: ', x.year)
Output:

date:  2021-12-05 00:00:00      week:  48       year:  2021
date:  2021-12-12 00:00:00      week:  49       year:  2021
date:  2021-12-19 00:00:00      week:  50       year:  2021
date:  2021-12-26 00:00:00      week:  51       year:  2021
date:  2022-01-02 00:00:00      week:  52       year:  2022

输出是有道理的,但是,这在我使用的过滤下不起作用:

df[(df['date'].year == x.year) & (df['date'].week == x.week)]

目前这个问题已经用创可贴解决了,但希望明年能完全发挥作用。

【问题讨论】:

    标签: python pandas date datetime


    【解决方案1】:

    这是一项功能,而不是错误。 周编号基于 ISO 8601,具体来说:“如果 1 月 1 日是周五、周六或周日,则为上一年的第 52 周或第 53 周”。您需要更改应用程序逻辑以包含该边缘情况。

    https://en.wikipedia.org/wiki/ISO_8601#Week_dates

    另外,根据 pandas 文档:

    weekofyearweek 已被弃用。请改用DatetimeIndex.isocalendar().week。”

    如果您同时切换到 x.isocalendar().weekx.isocalendar().year,您将获得一致的输出,尽管不是直观的输出:

    date:  2021-12-19 00:00:00      week:  50       year:  2021
    date:  2021-12-26 00:00:00      week:  51       year:  2021
    date:  2022-01-02 00:00:00      week:  52       year:  2021
    date:  2022-01-09 00:00:00      week:  1        year:  2022
    

    【讨论】:

    • 谢谢,我怎么能看到 .isocalendar() 的日期时间序列? (df['datetime'] 列)
    • @AkmalSoliev 不确定我是否理解您的问题;您的 x (for x in pd.date_range) 已经拥有该属性。您只需将 x.week 替换为 x.isocalendar().week,同样适用于 .year
    • 我将用于与列匹配的 date_range 对象,我遇到的问题是 1 月 1 日在调用 .year 时仍会显示为 2022,因此想知道我是否可以提取 isocalendar()从日期时间列?还是需要将其转换为时间戳?
    • df['date'].isocalendar().year 不起作用?
    • 不,得到,AttributeError: 'Series' object has no attribute 'isocalendar'
    【解决方案2】:

    您可以做什么 - 您可以使用以下属性在一周的开始日应用过滤:

    pd.Timestamp(2022, 1, 2).to_period('W').start_time
    

    输出

    Timestamp('2021-12-27 00:00:00')
    

    所以:

    import pandas as pd
    
    d = pd.DataFrame({"date":[pd.Timestamp(2022,1,2)]})
    
    d[d["date"].dt.to_period('W').apply(lambda x: x.start_time.isocalendar()[:2] == (2021, 52))]
    

    输出

            date
    0 2022-01-02
    

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2012-10-31
      • 2021-10-07
      相关资源
      最近更新 更多