python - 为什么 Pandas 会错误地评估一年中最后一天的周数?

标签 python python-3.x pandas datetime

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

如果你依赖周数作为输入,它会严重破坏你的 count ifs、max ifs 等。

最佳答案

根据@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

关于python - 为什么 Pandas 会错误地评估一年中最后一天的周数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50370433/

相关文章:

python - 如何使用 seaborn 为每条线绘制带有特定颜色和线型的特定点上的点的线图?

python - 使用多索引条件选择数据帧的子集

python - 高效的字节浮点乘法

python - Pandas 多索引 DataFrame : keep the N biggest entries of a column while grouping on level 1 index

python - 如何将文本行转换为有意义的单词

python - 断言 JSON 响应

Python3 : Writing data of bytes in a file

python - 获取已编译函数对象的函数

python - 如何根据柱状组的多(其他列)条件选择数据框行?

python-3.x - 必须先运行 readlines(),然后运行 ​​read()。有没有更有效的方法