Pandas DataFrame如何查询最接近的日期时间索引? [英] Pandas DataFrame How to query the closest datetime index?
本文介绍了Pandas DataFrame如何查询最接近的日期时间索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从Pandas DataFrame中查询最接近的索引?索引是DatetimeIndex
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
我尝试过:
df.index.get_loc(df.index[0], method='nearest')
但是它给了我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')
但是,如果我删除了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
推荐答案
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
这篇关于Pandas DataFrame如何查询最接近的日期时间索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文