Python - Filter Pandas DataFrame by Time



To filter DataFrame by time, use the loc and set the condition in it to fetch records. At first, import the required library βˆ’

import pandas as pd

Create a Dictionary of list 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-05-19', '2021-08-22']
   }

Creating a dataframe from the above dictionary of lists βˆ’

dataFrame = pd.DataFrame(d)

Now, let’s say we need to fetch cars purchased after a specific date. For this, we use loc βˆ’

resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"]

Example

Following is the complete 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-05-19', '2021-08-22']
   }

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

# fetch cars purchased after 15th July 2021
resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"]

# print filtered data frame
print"\nCars purchased after 15th July 2021: \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-05-19
5   Bentley         2021-08-22

Cars purchased after 15th July 2021:
       Car   Date_of_Purchase
1    Lexus         2021-08-12
5  Bentley         2021-08-22
Updated on: 2021-09-20T08:16:43+05:30

644 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements