Pandas到日期时间转换到2019年,第一周是wk0

2024-10-02 00:22:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾经用年份和周数来转换为某个求婚的日期。 它在2019年前运行良好,但当我试图导入2019年的wk1数据时,它就连线了。在

2019年1月1日至2019年1月3日

但恰恰相反,如果我用日期来转换成年和周,这是正确的。在

我能知道我的代码有什么问题吗?谢谢

d = {'year': [2018, 2018, 2018, 2019, 2019, 2019], 'week': [0, 1, 52, 0, 1, 2]}
df = pd.DataFrame(data=d)
df['date'] = pd.to_datetime(df['year'].map(str) + df['week'].map(str) + '-4', format='%Y%W-%w')
df['yearwk'] = pd.to_datetime(df['date'], format='%Y-%M-%D').dt.strftime('%YW%V')
print(df)

   year  week       date   yearwk
0  2018     0 2018-01-04  2018W01
1  2018     1 2018-01-04  2018W01
2  2018    52 2018-12-27  2018W52
3  2019     0 2019-01-03  2019W01
4  2019     1 2019-01-10  2019W02
5  2019     2 2019-01-17  2019W03

我使用给定的年份和星期数来转换为日期。理想情况下,2019年第1周应该在2018年12月31日至2019年1月5日之间,但它变成了2019年1月6日至2019年1月13日。 然后我用那个日期转换成年和周,结果就是我所期望的。在


Tags: to数据formatmapdfdatetimedateyear
1条回答
网友
1楼 · 发布于 2024-10-02 00:22:37

根据strftime() and strptime() Behavior

%W: Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.

%w: Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

您将4作为%w,表示您需要提供的星期四的日期。在

从星期一开始的2018年第一周(%W=1)是:1月1日-1月7日或1月4日(星期四)

从周一开始的2019年第一周(%W=1)是:1月7日-1月13日或1月10日(星期四)

对于2018年,前一周没有星期四,因此%W=0的输出与%W=1相同。但是,对于2019年,前一周有一个星期四,因此%W=0将在1月3日输出。在

相关问题 更多 >

    热门问题