如何将字符串数据框列转换为日期时间作为带有年和周的格式?

Emr*_*GEN 9 python datetime python-3.x pandas

样本数据:

Week      Price
2011-31    1.58
2011-32    1.9
2011-33    1.9
2011-34    1.9
Run Code Online (Sandbox Code Playgroud)

我有一个像上面这样的数据框,我想将“周”列类型从字符串转换为日期时间。

我的代码:

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

错误:

“ValueError:无法使用没有日期和年份的‘%W’或‘%U’”

jez*_*ael 10

您需要通过参数指定星期几%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
Run Code Online (Sandbox Code Playgroud)

用于:DatetimeIndexDataFrame.poprename

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
Run Code Online (Sandbox Code Playgroud)