Python - Filter Pandas DataFrame by Time Index

Given a Pandas DataFrame, we have to filter it by time index. By Pranit Sharma Last updated : September 26, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

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' and time is present in the format of 'HH:MM:SS'.

Here,

  • yy means year
  • mm means month
  • dd means day
  • HH means hours
  • MM means minutes
  • SS means seconds

Problem statement

Given a Pandas DataFrame, we have to filter it by time index.

Filtering Pandas DataFrame by Time Index

While accessing the date and time from datetime, we always get date and time together, here, we have a column with values each of string time. We will filter this DataFrame by time comparison.

Let us understand with the help of an example,

Python code to filter pandas dataframe by time index

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {'Time':['2013-10-16 08:00:00','2012-05-26 23:12:00','2010-03-06 18:30:00','2022-08-13 15:15:00','2011-05-11 11:59:00','2017-06-26 00:00:00']}

# Creating DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Filtering column by date
df = df.loc[df['Time'].values < '2013-10-16 08:00:00']

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Filter Pandas DataFrame by Time Index

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.