Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using isna() as a condition in a if else statement

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

df['LastTravelDate'] = np.where(df['TripEndDate'].isna(),df['TripStartDate'],df['TripEndDate'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading