gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:22 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com