我有一個這樣的資料框(這個資料在 bigquery 中。年周格式是%Y%U(星期從星期日開始):
data = {'yearweek': ['202140', '202139', '202138', '202137'], 'value': [452, 741, 475, 1000]}
df=pd.DataFrame(data)
yearweek value
202140 452
202139 741
202138 475
202137 1000
預期輸出:
yearweek value date
202140 452 04-10-2021
202139 741 27-09-2021
202138 475 20-09-2021
202137 1000 13-09-2021
我試過這個:
df['date'] = pd.to_datetime(df.yearweek '0', format='%Y-%W%w')
但收到此錯誤:
ValueError: time data '2021420' does not match format '%Y-%W%w' (match)
也試過:
df['datex'] = pd.to_datetime(df.yearweek , format='%Y-%W%w')
但又出錯了
ValueError: time data '202142' does not match format '%Y-%W%w' (match)
uj5u.com熱心網友回復:
您可以使用格式作為 format='%Y%U%w'
>>> import pandas as pd
>>> df = pd.DataFrame({'yearweek': ['202140', '202139', '202138', '202137'], 'value': [452, 741, 475, 1000]})
>>> df
yearweek value
0 202140 452
1 202139 741
2 202138 475
3 202137 1000
>>> df['date'] = pd.to_datetime(df.yearweek '0', format='%Y%U%w')
>>> df
yearweek value date
0 202140 452 2021-10-03
1 202139 741 2021-09-26
2 202138 475 2021-09-19
3 202137 1000 2021-09-12
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362967.html
上一篇:比較PHP中的日期
