0

I have to find difference between two date columns in python dataframe and to compare whether difference is greater than 120 or not

if working_data['CLAIMS_EVENT_DATE'] - working_data['LAST_LAPSED_DATE'] > 120:

I got below Error

invalid_comparison .format(dtype=left.dtype, typ=type(right).name))

TypeError: Invalid comparison between dtype=timedelta64[ns] and int

2
  • what about (working_data['CLAIMS_EVENT_DATE'] - working_data['LAST_LAPSED_DATE']).dt.days >120 Commented Oct 18, 2019 at 13:31
  • working_data is a dataframe name. CLAIMS_EVENT_DATE and LAST_LAPSED_DATE are column names Commented Oct 18, 2019 at 13:32

2 Answers 2

1

If compare both get timedeltas, so for compare are possible 2 solutions - compare days by Series.dt.days with Series.any if need test if at least one value match condition:

s = (working_data['CLAIMS_EVENT_DATE'] - working_data['LAST_LAPSED_DATE'])

if (s.dt.days > 120).any():
    print ('At least one value is higher')

Or compare by Timedelta:

if (s > pd.Timedelta(120, unit='d')).any():
    print ('At least one value is higher')

If need fitler rows use boolean indexing:

df = working_data[s.dt.days > 120]

Or:

df = working_data[s > pd.Timedelta(120, unit='d')]
Sign up to request clarification or add additional context in comments.

Comments

0
#Convert both columns to datetime format
working_data['CLAIMS_EVENT_DATE'] = pd.to_datetime(working_data['CLAIMS_EVENT_DATE'])
working_data['LAST_LAPSED_DATE'] = pd.to_datetime(working_data['LAST_LAPSED_DATE'])

#Calculate the difference between the days
working_data['Days'] = (working_data['LAST_LAPSED_DATE']                           
                        - working_data['CLAIMS_EVENT_DATE']).days

#Create a column 'Greater' and check whether difference is greater than 120 or not
working_data.loc[working_data.Days <= 120, 'Greater'] = 'False' 
working_data.loc[working_data.Days > 120, 'Greater'] = 'True' 

1 Comment

Yes, you are correct. The TypeError is due to the comparison between different datatypes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.