ADVERTISEMENT
ADVERTISEMENT

How to select DataFrame rows between two dates?

Learn how to select DataFrame rows between two dates?
Submitted by Pranit Sharma, on May 11, 2022

Pandas is a special tool which allows us to perform complex manipulations of data effectively and efficiently. Pandas is a vast library of thousands of amazing methods including various data structures, numerical data and datetime.

The datetime is a library in python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually date is present in the format of "yy-mm-dd".

Here,

  • yy means year
  • mm means month
  • dd means day

Here, we are going to learn how to select rows between two dates?

For this purpose, we will just simply compare the dates and filter our rows using pandas.DataFrame.loc Property.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example:

# Importing pandas package
import pandas as pd

# Creating a dictionary
data = {
    'Name': ['Harry', 'Suresh','Akash', 'Irfan'],
    'Salary': [50000, 35000, 42000, 38000],
    'Location': ['Madurai', 'Kolkata','Gurugram', 'Noida'],
    'DOB': ['2020-08-04', '2020-08-07', '2020-08-08', '2020-06-08']
}

# Creating DataFrame
df = pd.DataFrame(data)

# Display original DataFrame
print("Original DataFrame\n",df,"\n")

# Filtering rows based on comparison of dates, 
# for this purpose we need two random dates
date1 = '2020-08-05'
date2 = '2020-08-08'

result = (df['DOB'] > date1) & (df['DOB'] <= date2)

# Selecting rows from DataFrame
df = df.loc[result]

# Display Result
print(df)

Output:

Example: Select DataFrame rows between two dates

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.