gpt4 book ai didi

pandas - Pandas DataFrame如何查询最近的日期时间索引?

转载 作者:行者123 更新时间:2023-12-03 20:17:44 26 4
gpt4 key购买 nike

如何从Pandas DataFrame查询最接近的索引?索引是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

如果我尝试了同样的错误:

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'可以,但是那不是我想要的,我想从查询日期时间中找到最接近的索引

最佳答案

看来您首先需要通过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

关于pandas - Pandas DataFrame如何查询最近的日期时间索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42264848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com