Pandas DataFrame: How to query the closest datetime index?

Given a pandas dataframe, we have to query the closest datetime index.
Submitted by Pranit Sharma, on October 20, 2022

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.

Problem statement

We are given a DataFrame where an index is of datetime format, we need to apply a query for the closest index from the pandas DataFrame.

Query the closest datetime index

To query the closest datetime index, we will use the pandas.Index.get_loc() method which will allow us to get the first position and then we will select the value using square brackets [ ].

First, we are going to create a DataFrame where the datetime is the index format, we will then use pandas.Index.get_loc() method to find the position of the index and then we will select the index value.

Let us understand with the help of an example,

Python program to query the closest datetime index

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {'a':[1,2,3],'b':[4,5,6]}

ind = ['2016-11-13 20:00:10.617989120','2017-11-13 15:00:10.617989120','2018-12-17 23:00:11.617989120']
ind_ = [pd.to_datetime(i) for i in ind]

# Creating a DataFrame
df = pd.DataFrame(d,index=ind_)

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

# randomly we will search any of the index
dt = ind_[1]

# Selecting whole as a row
res = df.iloc[df.index.get_loc(dt, method='nearest')]

# Display Result
print('Result:\n',res)

Output

Example: Pandas DataFrame: How to query the closest datetime index?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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