2017-02-16 111 views
2

我如何查询Pandas DataFrame中最接近的索引?该指数是DatetimeIndexPandas DataFrame如何查询最近的日期时间索引?

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 

我尝试这样做:

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

,但它给我InvalidIndexError: Reindexing only valid with uniquely valued Index objects

同样的错误,如果我尝试这样做:

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

但如果我删除method='nearest'它的工作原理,但这不是我想要的,我想找到最接近的索引从我的查询日期时间

回答

1

看来你需要首先通过get_loc得到的位置,然后通过[]选择:

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 
+0

谢谢你的解决方案。我相信你的解决方案可以工作,但它只是对我不起作用... 这是我的索引类型

+0

你能解释一下吗?更多?它会返回错误的价值吗?问题出在这个带有真实数据的样本上? – jezrael

+0

dt = pd.to_datetime(“2016-11-13 22:01:25.450”); df.index.get_loc(dt,method ='nearest'); InvalidIndexError:Reindexing只对有唯一值的索引对象有效 –

0

我相信jezrael解决方案的工作,但不是我的数据框(我有不知道为什么)。这是我提出的解决方案。

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 
相关问题