Skip to main content
 首页 » 编程设计

python之在 Pandas 中,如何使用 "where"参数来查询日期时间索引列

2024年10月24日10kenshinobiy

我使用 append_to_multiple 将数据帧追加到 2 个表中,选择器是日期时间列。像这样。

store.append_to_multiple({'time': ['time'], 'data': ['field1', 'field2']},  
    df, selector='time') 

然后,现在我想使用带有 where 参数的 select_as_multiple 来查询 time 字段。
我想这样做,但查询日期时间字段。

store.select_as_multiple(['df1_mt', 'df2_mt'], where=['A>0', 'B>0'], 
    selector = 'df1_mt') 

那么,where 参数的元素必须是字符串是对的,如何使用日期时间索引进行查询?

请您参考如下方法:

如 docs 中所述,您可以使用 YYYYMMDD 整数/字符串,或内联 Timestamp 表达式。

In [20]: df = pd.DataFrame({'a':pd.date_range('2014-1-1', periods=300)}) 
 
In [21]: df.to_hdf('store.h5', 'df', format='table', data_columns=True) 
 
In [25]: pd.read_hdf('store.h5', 'df', where='a > 20141015') 
Out[25]:  
             a 
288 2014-10-16 
289 2014-10-17 
290 2014-10-18 
291 2014-10-19 
292 2014-10-20 
293 2014-10-21 
294 2014-10-22 
295 2014-10-23 
296 2014-10-24 
297 2014-10-25 
298 2014-10-26 
299 2014-10-27 
 
In [26]: pd.read_hdf('store.h5', 'df', where='a > Timestamp("10/15/2014")') 
Out[26]:  
             a 
288 2014-10-16 
289 2014-10-17 
290 2014-10-18 
291 2014-10-19 
292 2014-10-20 
293 2014-10-21 
294 2014-10-22 
295 2014-10-23 
296 2014-10-24 
297 2014-10-25 
298 2014-10-26 
299 2014-10-27