How can a Pandas DataFrame be sorted by date?

How can a Pandas DataFrame be sorted by date?

A Pandas DataFrame can be sorted by date by using the “sort_values” function and specifying the column containing the dates as the sorting criteria. This function will arrange the data in ascending or descending order based on the dates, allowing for easy analysis and comparison of data over time. Additionally, the “sort_index” function can be used to sort the DataFrame by the index, which is useful when the dates are set as the index. Overall, these sorting methods allow for efficient organization and manipulation of data based on chronological order in a Pandas DataFrame.

Sort a Pandas DataFrame by Date (With Examples)


Often you may want to sort a pandas DataFrame by a column that contains dates. Fortunately this is easy to do using the sort_values() function.

This tutorial shows several examples of how to use this function in practice.

Example 1: Sort by Date Column

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'sales': [4, 11, 13, 9],
                   'customers': [2, 6, 9, 7],
                   'date': ['2020-01-25', '2020-01-18', '2020-01-22', '2020-01-21']})

#view DataFrame
print(df)

   sales  customers        date
0      4          2  2020-01-25
1     11          6  2020-01-18
2     13          9  2020-01-22
3      9          7  2020-01-21

First, we need to use the to_datetime() function to convert the ‘date’ column to a datetime object:

df['date'] = pd.to_datetime(df['date'])

Next, we can sort the DataFrame based on the ‘date’ column using the sort_values() function:

df.sort_values(by='date')

        sales	customers	date
1	11	6	  2020-01-18
3	9	7	  2020-01-21
2	13	9	  2020-01-22
0	4	2	  2020-01-25

By default, this function sorts dates in ascending order. However, you can specify ascending=False to instead sort in descending order:

df.sort_values(by='date', ascending=False)

	sales	customers	date
0	4	2	  2020-01-25
2	13	9	  2020-01-22
3	9	7	  2020-01-21
1	11	6	  2020-01-18

Example 2: Sort by Multiple Date Columns

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'person': ['A', 'B', 'C', 'D'],
                   'order_date': ['2020-01-15', '2020-01-15', '2020-01-20', '2020-01-20'],
                   'receive_date': ['2020-01-25', '2020-01-18', '2020-01-22', '2020-01-21']})

#view DataFrame
print(df)

  person  order_date receive_date
0      A  2020-01-15   2020-01-25
1      B  2020-01-15   2020-01-18
2      C  2020-01-20   2020-01-22
3      D  2020-01-20   2020-01-21

We can use the sort_values function to sort the DataFrame by multiple columns by simply providing multiple column names to the function:

#convert both date columns to datetime objects
df[['order_date','receive_date']] = df[['order_date','receive_date']].apply(pd.to_datetime)

#sort DateFrame by order_date, then by receive_date
df.sort_values(by=['order_date', 'receive_date'])

        person	order_date	receive_date
1	B	2020-01-15	2020-01-18
0	A	2020-01-15	2020-01-25
3	D	2020-01-20	2020-01-21
2	C	2020-01-20	2020-01-22

The DataFrame is now sorted in ascending order by order_date, then in ascending order by receive_date.

How to Filter Pandas DataFrame Rows by Date
How to Convert Datetime to Date in Pandas
How to Convert Columns to DateTime in Pandas

Cite this article

stats writer (2024). How can a Pandas DataFrame be sorted by date?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-a-pandas-dataframe-be-sorted-by-date/

stats writer. "How can a Pandas DataFrame be sorted by date?." PSYCHOLOGICAL SCALES, 18 Apr. 2024, https://scales.arabpsychology.com/stats/how-can-a-pandas-dataframe-be-sorted-by-date/.

stats writer. "How can a Pandas DataFrame be sorted by date?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-can-a-pandas-dataframe-be-sorted-by-date/.

stats writer (2024) 'How can a Pandas DataFrame be sorted by date?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-a-pandas-dataframe-be-sorted-by-date/.

[1] stats writer, "How can a Pandas DataFrame be sorted by date?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, April, 2024.

stats writer. How can a Pandas DataFrame be sorted by date?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top