Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
Advertisements
