How to Sort a Pandas DataFrame by Date?


Python’s Pandas DataFrame defines the two-dimensional structure that consists of rows and columns. The main feature of pandas is an easier way of handing the given data. In Python, we have some in-built functions such as to_datetime(), sorted(), lambda, and, sort_value() will be Sort a Pandas DataFrame by Date.

Syntax

The following syntax is used in the examples-

to_datetime()

The to_datetime() is an in-built function in Python that convert string dates into date-time objects.

sorted()

The built-in function sorted() of Python states that the list can be sort as specified iterable objects.

lambda

This lambda function in Python is known as an anonymous function. It can be used when function objects are required. This function operates the main logical part of the program.

sort_values()

The sort_values() is an in-built function in Python that sort the dataframe in the sequence of ascending and descending order.

Using sort_values() function

In the following example, we will start the program by importing the pandas module that will be used to work with Dataframe by Date. Then create the variable d to define the input dictionary. Next, set the dataframe using the built-in function DataFrame() and store it in the variable df. Then set the format of the date using built-in function to_datetime and store it in the variable df[‘Date’]. Moving ahead to initialize the last variable named Date_result that stores the value as df.sort_value() which accepts two parameters- ‘Date’ and ascending = True to sort the dataframe in ascending order. Finally, it will print the result with the help of variable Date_result.

Example

import pandas as pd
# Create a sample DataFrame
d = { 'Date': ['2023-06-26', '2023-06-27', '2023-06-28', '2023-06-29'], 'Value': [100, 200, 300, 400] }
# Set the dataframe for date
df = pd.DataFrame(d)
# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'])
# Sort the dataframe in ascending order
Date_result = df.sort_values('Date', ascending=True)
# The final output
print("Result of pandas Dataframe by Date:\n", Date_result)

Output

 Result of pandas Dataframe by Date:
         Date  Value
0 2023-06-26    100
1 2023-06-27    200
2 2023-06-28    300
3 2023-06-29    400

Using sorted() function

In the following example, the program uses two main methods i.e. list comprehension and sorted() as a parameter of the built-in function DataFrame() to generate the result.

Example

import pandas as pd
# Create a sample DataFrame
d = { 'Date': ['2023-06-26', '2023-06-27', '2023-06-28', '2023-06-29'], 'Value': [11, 31, 456, 8534] }
# Create the dataframe
df = pd.DataFrame(d)
# Conversion of date into datetime format
df['Date'] = pd.to_datetime(df['Date'])
# using list comprehension and sorted()
res = pd.DataFrame(sorted(df.values, key=lambda x: x[0]), columns=df.columns)
# The final output
print("Result of pandas Dataframe by Date:\n", res)

Output

 Result of pandas Dataframe by Date:
         Date  Value
0 2023-06-26     11
1 2023-06-27     31
2 2023-06-28    456
3 2023-06-29   8534

Using inplace parameter in sort_values()

In the following example, the program uses built-in function to_datetime() that accepts the parameters as df[‘date’] to set the column of datetime format. Next, it will use the built-in function sort_values() that accepts two parameters- Date and inplace = true which means it sorts the Dataframe by date.

Example

import pandas as pd
# Create a sample DataFrame
data = { 'Date': ['2023-06-15', '2023-06-14', '2023-06-17', '2023-06-16'], 'Value': [10, 20, 30, 40] }
df = pd.DataFrame(data)
# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'])
# Sort the DataFrame by the Date column using the parameter inplace
df.sort_values('Date', inplace=True)
print(df)

Output

         Date  Value
1 2023-06-14     20
0 2023-06-15     10
3 2023-06-16     40
2 2023-06-17     30

Using to_datetime() function

In the following example, we will use the built-in function DataFrame() that accepts the parameter as variable data. Using this function will convert the data into the dataframe. The dataframe normally creates the data in 2-dimensional. Next, use the built-in function to_datetime() that set the format of the given input date and generates the result.

Example

import pandas as pd
# Create a sample DataFrame
data = { 'Date': ['2023-06-15', '2023-06-14', '2023-06-17', '2023-06-16'], 'Value': [10, 20, 30, 40], 'Attendance': ['Present', 'Present', 'Absent', 'Absent'] }
# Create the dataframe for date
df = pd.DataFrame(data)
# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'])
print("The Dataframe of Date result:\n", df)

Output

 The Dataframe of Date result:
         Date  Value Attendance
0 2023-06-15     10    Present
1 2023-06-14     20    Present
2 2023-06-17     30     Absent
3 2023-06-16     40     Absent

Conclusion

The Pandas is an open-source library that represents the Python top library. In this article, we discussed the various methods where it uses some built-in functions such as to_datetime(), DataFrame(), etc. to fulfilling the specific conditions and operations. This type of program is generally used in the field of Data Science.

Updated on: 17-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements