Wednesday, July 3, 2024
HomeLanguagesPythonFilter Pandas DataFrame by Time

Filter Pandas DataFrame by Time

In this article let’s see how to filter pandas data frame by date. So we can filter python pandas data frame by date using the logical operator and loc() method. In the below examples we have a data frame that contains two columns the first column is Name and another one is DOB.

Example 1: filter data that’s DOB is greater than 1999-02-5.

Python




import pandas as pd
  
# create data frame
Data = {'Name': ['Mukul', 'Rohan', 'Mayank',
                          'Shubham', 'Aakash'],
  
        'DOB': ['1997-04-24', '1998-05-25', '1999-04-11',
                '2000-11-15', '1998-06-28']}
  
df = pd.DataFrame(Data)
  
# print original data frame
print(df)
  
# filter data frame
New_df = df.loc[df["DOB"] >= "1999-02-5"]
  
# print filtered data frame
print(New_df)


Output:

Example 2: filter data between two date. 

Python




import pandas as pd
  
# create data frame
Data = {'Name': ['Mukul', 'Rohan', 'Mayank',
                          'Shubham', 'Aakash'],
  
        'DOB': ['1997-04-24', '1998-05-25', '1999-04-11',
                '2000-11-15', '1998-06-28']}
df = pd.DataFrame(Data)
  
# print original data frame
print(df)
  
Date1 = df["DOB"] >= "1998-04-24"
Date2 = df["DOB"] <= "1999-1-31"
  
# filter data between 1998-04-24 to 1999-01-31
New_df = df.loc[Date1 & Date2]
  
# print the filtered data frame
print(New_df)


Output:

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments