Home » Pandas: How to Find Earliest Date in a Column

Pandas: How to Find Earliest Date in a Column

by Erma Khan

You can use the following methods to find the earliest date in a column of a pandas DataFrame:

Method 1: Find Earliest Date in Column

df['date_column'].min()

Method 2: Find Row with Earliest Date in Column

df.iloc[df['date_column'].argmin()]

The following examples shows how to use this syntax in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'date': pd.to_datetime(['2022-04-01', '2022-02-12',
                                           '2022-06-13', '2022-02-04',
                                           '2022-07-01', '2022-02-19',
                                           '2022-12-03', '2022-04-04']),
                   'sales': [12, 15, 24, 24, 14, 19, 12, 38]})

#view DataFrame
print(df)

        date  sales
0 2022-04-01     12
1 2022-02-12     15
2 2022-06-13     24
3 2022-02-04     24
4 2022-07-01     14
5 2022-02-19     19
6 2022-12-03     12
7 2022-04-04     38

Example 1: Find Earliest Date in Column

We can use the following code to find the earliest date in the date column of the DataFrame:

#find earliest date in 'date' column
df['date'].min()

Timestamp('2022-02-04 00:00:00')

From the output we can see that the earliest date in the date column is 2/4/2022.

Note: If you want to find the most recent date, simply change min() to max() in the code.

Example 2: Find Row with Earliest Date in Column

We can use the following code to find the row with the earliest date in the date column of the DataFrame:

#find row with earliest date in 'date' column
df.iloc[df['date'].argmin()]

date     2022-02-04 00:00:00
sales                     24
Name: 3, dtype: object

The output displays the entire row that contains the earliest date in the date column.

For example, we can see the following values in this row:

  • date: 02-04-2022
  • sales: 24

If you only want to know the index position of the row with the earliest date, you can replace .iloc with .index as follows:

#find index position of row with earliest date in 'date' column
df.index[df['date'].argmin()]

3

This tells us that the row with index position 3 contains the earliest date in the date column.

Note: If you want to find the row with the most recent date, simply change argmin() to argmax() in the code.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Add and Subtract Days from a Date in Pandas
How to Select Rows Between Two Dates in Pandas
How to Create Date Column from Year, Month and Day in Pandas

Related Posts