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

subtracting 2 date columns in dataframe

I have the following pandas dataframe

enter image description here

I want to subtract date_of_birth from date_of_death to make a new column, "years_lived" to contain the years lived. I tried all 3 ways below (individually of course)

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

df['years_lived'] = (df['date_of_death'] - df['date_of_birth']).dt.days
df['years_lived'] = df['date_of_death'].sub(df['date_of_birth'], axis=0)
df['years_lived'] = df['date_of_death'] - df['date_of_birth']

but I got a TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’

>Solution :

df['years_lived'] = pd.to_datetime(df['date_of_death']) - pd.to_datetime(df['date_of_birth'])
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