Home > Software engineering >  Converting integer values to week (year-week format)
Converting integer values to week (year-week format)

Time:04-25

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:

import pandas as pd
import numpy as np
c=15
s={'week':[1,2,3,4,5,6,7,8],'Sales':[10,20,30,40,50,60,70,80]}
p=pd.DataFrame(data=s)

Output-

enter image description here

Desired O/p in week column should be in date time format.

enter image description here

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?

CodePudding user response:

You can use .apply():

import datetime
p['week'] = p['week'].apply(
    lambda x: datetime.datetime.strptime(f'2021-{x:02}-1', '%Y-%W-%u')
)

This outputs:

        week  Sales
0 2021-01-04     10
1 2021-01-11     20
2 2021-01-18     30
3 2021-01-25     40
4 2021-02-01     50
5 2021-02-08     60
6 2021-02-15     70
7 2021-02-22     80
  • Related