Python Pandas: weekly columns(int) to Timestamp columns conversion (in weeks)

这一生的挚爱 提交于 2020-02-05 13:07:55

问题


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

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')

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


回答1:


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

Source - http://strftime.org/:

%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)


来源:https://stackoverflow.com/questions/48260456/python-pandas-weekly-columnsint-to-timestamp-columns-conversion-in-weeks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!