Python Pandas:每周列(int)到时间戳列的转换(以周为单位) [英] Python Pandas: weekly columns(int) to Timestamp columns conversion (in weeks)

查看:790
本文介绍了Python Pandas:每周列(int)到时间戳列的转换(以周为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DF,每周栏如下.我想将列索引更改为时间戳.这是我的df.columns

I have a df with weekly columns as below. I want to change my column index to timestamp. Here is my df.columns

df.columns:
Int64Index([201601, 201602, 201603, 201604, 201605, 201606, 201607,
        201608, 201609,
        ...],
       dtype='int64', name='timeline', length=104)

df.columns[0]:
201553

我想将df.columns更改为时间戳,如下所示:

I want to change my df.columns into timestamp as below

 df.columns:
 DatetimeIndex(['2016-01-04', '2016-01-11', '2016-01-18', '2016-01-25',
           '2016-02-01', '2016-02-08', '2016-02-15', '2016-02-22',
           '2016-02-29'.....],
           dtype='int64', name='timeline', length=104)
df.columns[0]:
Timestamp('2016-01-04 00:00:00')

最下面的一行是我的df.columns采用int格式,表示yyyyww值.从这个int,我想将其更改为Timestamp,以显示每周的星期一日期.请让我知道更改此问题的好方法.谢谢你

Bottom line is that my df.columns are in int format that indicates the yyyyww value. From this int, I want to change it to Timestamp that shows date of Monday of each week. Please let me know a good way to change this. THank you

推荐答案

您可以使用

You can use to_datetime, but first add 1 for Mondays and use %W with%w:

来源-http://strftime.org/:

%w 工作日为十进制数字,其中0是星期日,6是星期六.
%W 是一年中的第几周(星期一为一周中的第一天),以十进制数表示.在新的一年中,第一个星期一之前的所有天均视为在第0周.

%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
%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.

a = pd.Int64Index([201601, 201602, 201603, 201604, 201605, 201606, 201607,
        201608, 201609])

print (pd.to_datetime(a.astype(str) + '1', format='%Y%W%w'))
DatetimeIndex(['2016-01-04', '2016-01-11', '2016-01-18', '2016-01-25',
               '2016-02-01', '2016-02-08', '2016-02-15', '2016-02-22',
               '2016-02-29'],
              dtype='datetime64[ns]', freq=None)

这篇关于Python Pandas:每周列(int)到时间戳列的转换(以周为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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