Why pandas max function does not return the right max date?

Viewed 532

I wanted to get the max date from a column in a DataFrame, but the results are wrong?
What I am doing wrong?

df = pd.DataFrame.from_dict({'date':['31.12.2014', '03.10.2015','02.01.2013', '05.01.2013', '14.10.2015']})

the result of df.date.max() is '31.12.2014' and not '14.10.2015'? why?

2 Answers

First convert your date column to datetime format, and then check for max or min values

import pandas as pd

df = pd.DataFrame.from_dict({'date':['31.12.2014', '03.10.2015','02.01.2013', '05.01.2013', '14.10.2015']})

# Convert to datetime format
df['date'] = pd.to_datetime(df['date'])

# Print max value
print(df['date'].max())

If you want the strings to be compared as a datetime object this should help.

df['date'].astype('datetime64[ns]').max()
Related