问题
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