Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame How to query the closest datetime index?

How do i query for the closest index from a Pandas DataFrame? The index is DatetimeIndex

2016-11-13 20:00:10.617989120   7.0 132.0 2016-11-13 22:00:00.022737152   1.0 128.0 2016-11-13 22:00:28.417561344   1.0 132.0 

I tried this:

df.index.get_loc(df.index[0], method='nearest') 

but it give me InvalidIndexError: Reindexing only valid with uniquely valued Index objects

Same error if I tried this:

dt = datetime.datetime.strptime("2016-11-13 22:01:25", "%Y-%m-%d %H:%M:%S") df.index.get_loc(dt, method='nearest') 

But if I remove method='nearest' it works, but that is not I want, I want to find the closest index from my query datetime

like image 823
Bryan Fok Avatar asked Feb 16 '17 04:02

Bryan Fok


People also ask

How do I select a specific index in pandas?

Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc. Indexing in Pandas means selecting rows and columns of data from a Dataframe.

How do I compare time in pandas?

Comparison between pandas timestamp objects is carried out using simple comparison operators: >, <,==,< = , >=. The difference can be calculated using a simple '–' operator. Given time can be converted to pandas timestamp using pandas. Timestamp() method.


1 Answers

It seems you need first get position by get_loc and then select by []:

dt = pd.to_datetime("2016-11-13 22:01:25.450") print (dt) 2016-11-13 22:01:25.450000  print (df.index.get_loc(dt, method='nearest')) 2  idx = df.index[df.index.get_loc(dt, method='nearest')] print (idx) 2016-11-13 22:00:28.417561344 
#if need select row to Series use iloc s = df.iloc[df.index.get_loc(dt, method='nearest')] print (s) b      1.0 c    132.0 Name: 2016-11-13 22:00:28.417561344, dtype: float64 
like image 96
jezrael Avatar answered Sep 23 '22 03:09

jezrael