Home > Enterprise >  If date is leap day (29-Feb) change to 28-Feb
If date is leap day (29-Feb) change to 28-Feb

Time:05-22

In a Pandas dataframe i need to change all leap days cells in a specific column (they should be changed to 28 Feb). So, for example, 2020/02/29 should become 2020/02/28.

I tried the following, but didn't work:

df.loc[((df['Date'].dt.month == 2) & (df['Date'].dt.day == 29)), 'Date'] = df['Date']   timedelta-(1)

Any ideas? Thanks

CodePudding user response:

You can use np.where:

df["Date"] = np.where((df["Date"].dt.month == 2) & \
                      (df["Date"].dt.day == 29),
                      df["Date"] - pd.DateOffset(days=1),
                      df["Date"])

If you look closely, you have written timedelta-(1) which returns an error. Using your method works fine if you instead write timedelta(-1).

  • Related