I am trying to convert one of the dataframes I have to year-week format to use it in my time series modeling, but I am not sure how would I be able to do this?
Here is my code:
JavaScript
x
6
1
import pandas as pd
2
import numpy as np
3
c=15
4
s={'week':[1,2,3,4,5,6,7,8],'Sales':[10,20,30,40,50,60,70,80]}
5
p=pd.DataFrame(data=s)
6
Output-
Desired O/p in week column should be in date time format.
The datatype was an int in the 1st dataframe, but needs to be in datetime, where 2021 is year and 1 is week. (1st week of year 2021) How would I be able to do this?
Advertisement
Answer
You can use .apply()
:
JavaScript
1
5
1
import datetime
2
p['week'] = p['week'].apply(
3
lambda x: datetime.datetime.strptime(f'2021-{x:02}-1', '%Y-%W-%u')
4
)
5
This outputs:
JavaScript
1
10
10
1
week Sales
2
0 2021-01-04 10
3
1 2021-01-11 20
4
2 2021-01-18 30
5
3 2021-01-25 40
6
4 2021-02-01 50
7
5 2021-02-08 60
8
6 2021-02-15 70
9
7 2021-02-22 80
10