Python Pandas – Filter DataFrame between two dates

PythonServer Side ProgrammingProgramming

To filter DataFrame between two dates, use the dataframe.loc. At first, import the required library −

import pandas as pd

Create a Dictionary of lists with date records −

d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-02-19', '2021-08-22']
   }

Creating dataframe from the above dictionary of lists

dataFrame = pd.DataFrame(d)

Fetch car purchased between two dates i.e. 1st Date: 2021-05-10 and 2nd Date: 2021-08-25 −

resDF = dataFrame.loc[(dataFrame["Date_of_Purchase"] >= "2021-05-10") & (dataFrame["Date_of_Purchase"] <= "2021-08-25")]

Example

Following is the code −

import pandas as pd

# dictionary of lists
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-02-19', '2021-08-22']
   }

# creating dataframe from the above dictionary of lists
dataFrame = pd.DataFrame(d)
print"DataFrame...\n",dataFrame

# fetch car purchased between two dates
# 1st Date: 2021-05-10
# 2nd Date: 2021-08-25
resDF = dataFrame.loc[(dataFrame["Date_of_Purchase"] >= "2021-05-10") & (dataFrame["Date_of_Purchase"] <= "2021-08-25")]

# print filtered data frame
print"\nCars purchased between 2 dates: \n",resDF

Output

This will produce the following output −

DataFrame...
        Car   Date_of_Purchase
0       BMW         2021-07-10
1     Lexus         2021-08-12
2      Audi         2021-06-17
3  Mercedes         2021-03-16
4    Jaguar         2021-02-19
5   Bentley         2021-08-22

Cars purchased between 2 dates:
       Car   Date_of_Purchase
0      BMW         2021-07-10
1    Lexus         2021-08-12
2     Audi         2021-06-17
5  Bentley         2021-08-22
raja
Published on 20-Sep-2021 08:59:47
Advertisements