Search code examples
pythonstringpandasconcatenationstring-concatenation

pandas conditional str concat with a Datetime column


I would like to join only the day-ahead with the year of my Date column to make it look like day-ahead_2019 or day-ahead_2018 depending on the year in Date column

I have two columns:

DELIVERY_PERIOD   
day-ahead
day-ahead
day-ahead
day-ahead
week1_2019
week2_2018

and,

Date
13/05/2019
14/05/2019
11/05/2019
10/05/2019

I tried to use str.cat but it doesnt work for datetime64 for my Date column

       df.DELIVERY_PERIOD == 'day-ahead' = df.str.cat(df.Date.dt.year)

error came up as it is not str type data i thought about the other way around which is create new columns to get year from the Date.dt.year, convert it to str and only join with day-ahead but i think this would be a long way around i welcome any suggestions


Solution

  • I would do it like this,

    assuming your dataframe is called df

    you can pass the astype function to transform your series into a string and pass this back to your new or existing series.

    df['DELIVERY_PERIOD'] = df.loc[df['DELIVERY_PERIOD'] == 'day-ahead', 'DELIVERY_PERIOD'] = df['DELIVERY_PERIOD'] + '_' + df['Date'].dt.year.astype(str)
    print(df)
    
    
     DELIVERY_PERIOD    Date
    0   day-ahead_2019  2019-05-13
    1   day-ahead_2019  2019-05-14
    2   day-ahead_2019  2019-11-05
    3   day-ahead_2019  2019-11-05