Home > Software design >  Using isna() as a condition in a if else statement
Using isna() as a condition in a if else statement

Time:11-19

I have a df that looks like the following with many more rows:

LastTravelDate TripStartDate TripEndDate
2021-07-10 2021-08-16 NaT
2021-08-28 2021-09-30 NaT
2021-07-29 2021-09-27 2021-09-28

I am trying to write a loop that goes through every row in the df and sets the ith value of LastTravelDate equal to the ith value of TripEndDate. Wherever TripEndDate is equal to NaT I would like the script to set the ith value of LastTravelDate to the corresponding value in TripStartDate.

My issue is that the code seems to ignore all the details in the if/else statement and just sets all df.LastTravelDate equal to df.TripStartDate. What should happen is that df.LastTravelDate and df.TripStartDate are only equal wherever df.TripEndDate is null. However, these become equal in every instance. Below is the full code I am using.

for i in range(df.shape[0]): 
    if np.any(df.loc[df.TripEndDate.isna()]):
        df["LastTravelDate"][i] = df.TripStartDate[i]
    else:
        df["LastTravelDate"][i] = df.TripEndDate[i]
           

Thank you

CodePudding user response:

For a vectorized approach you can use np.where():

df['LastTravelDate'] = np.where(df['TripEndDate'].isna(),df['TripStartDate'],df['TripEndDate'])
  • Related