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

Bry*_*Fok 13 dataframe pandas

如何从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
Run Code Online (Sandbox Code Playgroud)

我试过这个:

df.index.get_loc(df.index[0], method='nearest')
Run Code Online (Sandbox Code Playgroud)

但它给了我 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')
Run Code Online (Sandbox Code Playgroud)

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

小智 33

DatetimeIndex.get_loc现在已被弃用,取而代之的是DatetimeIndex.get_indexer...

\n
ts = pd.to_datetime(\'2022-05-26 13:19:48.154000\')        #\xc2\xa0example time\niloc_idx = df.index.get_indexer([ts], method=\'nearest\')  # returns absolute index into df e.g. array([5])\nloc_idx = df.index[iloc_idx]                             # if you want named index\n\nmy_val = df.iloc[iloc_idx]\nmy_val = df.loc[loc_idx]                                 # as above so below...\n
Run Code Online (Sandbox Code Playgroud)\n


jez*_*ael 20

看来你需要先获得位置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
Run Code Online (Sandbox Code Playgroud)
#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
Run Code Online (Sandbox Code Playgroud)

  • 有什么办法可以同时查询多个日期时间?get_loc只接受标量值。 (2认同)
  • 正如 @HarryChil 所提到的,“DatetimeIndex.get_loc”现在已被弃用,取而代之的是“DatetimeIndex.get_indexer”。此方法需要一个列表,因此如果您想按照 @fhchl 的要求查询多个日期时间,也是转到方法 (2认同)