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

How do I combine two columns to create day-month-year in pandas python?

I want to combine the columns ‘Year’ and ‘Period’ into one column and to clean up date so it reads like day-month-year. ‘Year’ is an integer and ‘Period’ is an object. I’m having trouble combining and cleaning up the dates.

    Series Id   Year    Period  Value
0   CUSR0000SAF1    2012    M01 232.213
1   CUSR0000SAF1    2012    M02 232.140
2   CUSR0000SAF1    2012    M03 232.591
3   CUSR0000SAF1    2012    M04 233.044
4   CUSR0000SAF1    2012    M05 233.219

This is what I had:

df[‘Year’] = pd.to_datetime(df[‘Year’], format="%d/%m/%Y")

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

>Solution :

df['day_month_year'] = df.Year.astype(str) + df.Period.astype(str)
df['day_month_year'] = pd.to_datetime(df['day_month_year'], format="%YM%m").dt.strftime("%d/%m/%Y")

                  Id    Year    Per   Value day_month_year
0   0   CUSR0000SAF1    2012    M01 232.213 01/01/2012
1   1   CUSR0000SAF1    2012    M02 232.140 01/02/2012
2   2   CUSR0000SAF1    2012    M03 232.591 01/03/2012
3   3   CUSR0000SAF1    2012    M04 233.044 01/04/2012
4   4   CUSR0000SAF1    2012    M05 233.219 01/05/2012
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