简体   繁体   English

如何将字符串数据框列转换为datetime作为年份和周的格式?

[英]How to convert string dataframe column to datetime as format with year and week?

Sample Data: 样本数据:

Week      Price
2011-31    1.58
2011-32    1.9
2011-33    1.9
2011-34    1.9

I have a dataframe like above and I wanna convert 'Week' column type from string to datetime. 我有一个像上面这样的数据框,我想将'Week'列类型从字符串转换为datetime。

My Code: 我的代码:

data['Date_Time'] = pd.to_datetime(data.Week, format='%Y-%W')
data = data.drop(['Week'], axis=1)
data.index = data.Date_Time

Error: 错误:

'ValueError: Cannot use '%W' or '%U' without day and year' 'ValueError:没有日期和年份,不能使用'%W'或'%U'

%W uses Monday as the first day of the week. %W使用星期一作为一周的第一天。

import datetime
week = '2011-31'
date=datetime.datetime.strptime(week + '-1', "%Y-%W-%w")
print(date)

See this: https://repl.it/@ibrahimth/EvergreenNutritiousEmbeds 请参阅: https//repl.it/@ibrahimth/EvergreenNutritiousEmbeds

You need specify day of week by parameter %w : 您需要通过参数%w指定星期几:

data['Date_Time'] = pd.to_datetime(data.Week + '0', format='%Y-%W%w')
print (data)
      Week  Price  Date_Time
0  2011-31   1.58 2011-08-07
1  2011-32   1.90 2011-08-14
2  2011-33   1.90 2011-08-21
3  2011-34   1.90 2011-08-28

For DatetimeIndex use DataFrame.pop with rename : 对于DatetimeIndex使用DataFrame.pop rename

data.index = pd.to_datetime(data.pop('Week') + '0', format='%Y-%W%w').rename('Date')
print (data)
            Price
Date             
2011-08-07   1.58
2011-08-14   1.90
2011-08-21   1.90
2011-08-28   1.90

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM