使用 pandas 将一年中的星期解析为日期时间对象 [英] Parsing week of year to datetime objects with pandas

查看:99
本文介绍了使用 pandas 将一年中的星期解析为日期时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

     A    B    C     D yearweek
0  245   95   60    30  2014-48
1  245   15   70    25  2014-49
2  150  275  385   175  2014-50
3  100  260  170   335  2014-51
4  580  925  535  2590  2015-02
5  630  126  485  2115  2015-03
6  425   90  905  1085  2015-04
7  210  670  655   945  2015-05

最后一列包含年份以及星期数.是否可以使用pd.to_datetime将其转换为datetime列?

The last column contains the the year along with the weeknumber. Is it possible to convert this to a datetime column with pd.to_datetime?

我尝试过:

pd.to_datetime(df.yearweek, format='%Y-%U')

0   2014-01-01
1   2014-01-01
2   2014-01-01
3   2014-01-01
4   2015-01-01
5   2015-01-01
6   2015-01-01
7   2015-01-01
Name: yearweek, dtype: datetime64[ns]

但是该输出是不正确的,尽管我相信%U应该是星期数的格式字符串.我在这里想念什么?

But that output is incorrect, while I believe %U should be the format string for week number. What am I missing here?

推荐答案

您需要另一个参数来指定日期-选中:

You need another parameter for specify day - check this:

df = pd.to_datetime(df.yearweek.add('-0'), format='%Y-%W-%w')
print (df)
0   2014-12-07
1   2014-12-14
2   2014-12-21
3   2014-12-28
4   2015-01-18
5   2015-01-25
6   2015-02-01
7   2015-02-08
Name: yearweek, dtype: datetime64[ns]

这篇关于使用 pandas 将一年中的星期解析为日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆