Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting integer values to week (year-week format)

I am trying to convert one of the dataframe I have to year-week format to use it in my time series modelling, 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-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

enter image description here

The datatype was in 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?

>Solution :

You can use .apply():

import datetime
p['week'] = p['week'].apply(
    lambda x: datetime.datetime.strptime(f'2021-{x:02}-1', '%Y-%U-%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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading