【问题标题】:Why does Pandas incorrectly evaluate the week count of the last day of the year?为什么 Pandas 会错误地计算一年中最后一天的周数?
【发布时间】:2018-05-16 12:03:10
【问题描述】:
import pandas as pd    

t1 = pd.Timestamp('2018-01-01')
print(t1.week)

t364 = pd.Timestamp('2018-12-30')
print(t364.week)

t365 = pd.Timestamp('2018-12-31')
print(t365.week)

输出:

1
52
1

如果您依赖周数作为输入,它会严重影响您的计数 ifs、max ifs 等。

【问题讨论】:

  • 这可能与364/7 = 52365/7 = 52.1428571429 有关吗?
  • 它没有。请参阅en.wikipedia.org/wiki/ISO_week_date,尤其是“每周从星期一开始”。每周的年份是星期四所在的公历年,所以 t365 落入 2019 年的第一周
  • 就是这样。虽然很不合逻辑。
  • 要么是这个系统,要么是周数不完整(不是从星期一开始,没有 7 天)
  • "do" 和捕获组 "e" 和可选的 "s"…啊,该死的大脑…

标签: python python-3.x pandas datetime


【解决方案1】:

根据@zeeMonkeez 的评论,pandas 使用ISO week date conventions

一种解决方法是转换为 datetime,从年初提取天数,然后除以 7:

import pandas as pd
from math import ceil

def weeker(x):
    return ceil(x.to_pydatetime().timetuple().tm_yday / 7)

t1 = pd.Timestamp('2018-01-01')
print(t1.week, weeker(t1))  # 1 1

t364 = pd.Timestamp('2018-12-30')
print(t364.week, weeker(t364))  # 52 52

t365 = pd.Timestamp('2018-12-31')
print(t365.week, weeker(t365))  # 1 53

【讨论】:

    猜你喜欢
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    相关资源
    最近更新 更多