alexv
alexv

Reputation: 65

Compare dates in python pandas

I have 2 panda datetime columns and I want to compare them as following:

#check if the Date_Jan precedes Date_Feb
df['find_preceding'] = df.apply(lambda x: x.Date_Jan < x.Date_Feb, axis =1) # works 

# check if the Date_Jan follows Date_Feb
df['find_following'] = df.apply(lambda x: x.Date_Jan > x.Date_Feb, axis =1) # works

# check if Date_Jan and Date_Feb are the same    
df['find_same'] = df.apply(lambda x: x.Date_Jan == x.Date_Feb, axis =1) # works 

# check if Date_Jan is NaT and Date_Feb is a date
df['check_NaT_and_valid'] = df.apply(lambda x: x.Date_Jan == 'NaT' and x.Date_Feb != 'NaT', axis =1) # NOT working

Upvotes: 0

Views: 402

Answers (1)

jhomr
jhomr

Reputation: 487

Try using lambda x: x.Date_Jan == pd.NaT or lambda x: x.Date_Jan.isnull().

Your current code is looking for a string called 'NaT' which is not what it actually is.

For February it would be Date_Feb != pd.NaT or Date_Feb.isnotnull()

Upvotes: 1

Related Questions