gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:22:37 25 4
gpt4 key购买 nike

我有一个每周列的 df,如下所示。我想将列索引更改为时间戳。这是我的 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 更改为时间戳,如下所示

 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 开始,我想将其更改为显示每周星期一日期的时间戳。请告诉我一个改变这种情况的好方法。谢谢您

最佳答案

您可以使用to_datetime ,但首先为 Monday 添加 1 并将 %W%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)

关于Python Pandas : weekly columns(int) to Timestamp columns conversion (in weeks),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48260456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com