
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Python - Filter Pandas DataFrame with numpy
- Python Pandas – Filter DataFrame between two dates
- Processing time with Pandas DataFrame
- Python Pandas - Subset DataFrame by Column Name
- Create a Pandas Dataframe by appending one row at a time
- Python - How to Group Pandas DataFrame by Month?
- Python - How to Group Pandas DataFrame by Days?
- Python – Sort grouped Pandas dataframe by group size?
- Python - How to Group Pandas DataFrame by Year?
- Python - How to Group Pandas DataFrame by Minutes?
- Filter the rows – Python Pandas
- Python – Descending Order Sort grouped Pandas dataframe by group size?
- Python – Ascending Order Sort grouped Pandas dataframe by group size?
- Python – Merge two Pandas DataFrame
- Python - Grouping columns in Pandas Dataframe

Advertisements