Suhas_mudam
Suhas_mudam

Reputation: 195

To replace the date value based on the condition in a particular column using pandas

In my dataframe there is a date column in the format "%d/%m/%Y".

I want to replace the dates which are greater than today dates with the today's date.

EX:  Date
    --------
    10/05/2019
    06/06/2019
    20/08/2019
    30/09/2020

Expected output:

   Date
------------
 10/05/2019
 06/06/2019
 06/06/2019
 06/06/2019

Upvotes: 1

Views: 2613

Answers (1)

jezrael
jezrael

Reputation: 862406

Convert column to datetimes, compare and set today dates:

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
today = pd.Timestamp.today().floor('d')
df.loc[df['Date'] > today, 'Date'] = today
print (df)
        Date
0 2019-05-10
1 2019-06-06
2 2019-06-06
3 2019-06-06

Last if necessary same format use Series.dt.strftime:

df['Date'] = df['Date'].dt.strftime('%d/%m/%Y')
print (df)
         Date
0  10/05/2019
1  06/06/2019
2  06/06/2019
3  06/06/2019

Alternative with set only filtered rows to final format of datetimes:

d = pd.to_datetime(df['Date'], format='%d/%m/%Y')
today = pd.Timestamp.today().floor('d').strftime('%d/%m/%Y')
df.loc[d > today, 'Date'] = today
print (df)
         Date
0  10/05/2019
1  06/06/2019
2  06/06/2019
3  06/06/2019

Upvotes: 2

Related Questions