Skip to main content
 首页 » 编程设计

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

2024年12月31日7落叶无声

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