Pandas DataFrame How to request the nearest datetime index?

How do I request the closest index from a Pandas DataFrame? DatetimeIndex Index

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 he gives 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 delete method='nearest', it works, but I don’t want it, I want to find the closest index from my datetime query

+4
source share
2 answers

It seems you need to get the position first get_locand then choose []:

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
+3
source

I believe that jezrael's solution works, but not on my information frame (which I don’t know why). This is the solution I came across.

from bisect import bisect #operate as sorted container
timestamps = np.array(df.index)
upper_index = bisect(timestamps, np_dt64, hi=len(timestamps)-1) #find the upper index of the closest time stamp
df_index = df.index.get_loc(min(timestamps[upper_index], timestamps[upper_index-1],key=lambda x: abs(x - np_dt64))) #find the closest between upper and lower timestamp
0
source

Source: https://habr.com/ru/post/1669896/


All Articles