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

Time:12-29

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")

CodePudding user response:

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
  • Related