Skip to main content
 首页 » 编程设计

python Pandas : detecting existence of timestamp in Series

2025年05月04日12zhengyun_ustc

我正在尝试检测系列中是否有时间戳,但即使它存在,它也会返回 false。有人可以帮我找出为什么这不起作用吗?

In [149]: results.index[1] in time_range[0] 
Out[149]: False 
 
In [150]: results.index[1] 
Out[150]: Timestamp('2013-07-05 00:00:00') 
 
In [151]: time_range[0][19] 
Out[151]: Timestamp('2013-07-05 00:00:00') 
 
In [152]: type(time_range[0][19]) 
Out[152]: pandas.tslib.Timestamp 
 
In [153]: type(results.index[1]) 
Out[153]: pandas.tslib.Timestamp 
 
In [154]: type(time_range[0]) 
Out[154]: pandas.core.series.Series 

请您参考如下方法:

您可以对 pd.Series.index 使用 .isin 运算符。

import pandas as pd 
import numpy as np 
 
ser = pd.Series(np.random.randn(10), index=pd.date_range('2013-07-05 00:00:00', periods=10, freq='D')) 
 
2013-07-05   -1.1967 
2013-07-06    0.2598 
2013-07-07   -0.0319 
2013-07-08   -0.7489 
2013-07-09   -0.3605 
2013-07-10    0.0354 
2013-07-11    0.5557 
2013-07-12   -1.9588 
2013-07-13    1.4929 
2013-07-14    1.3351 
Freq: D, dtype: float64 
 
 
time_range = [pd.Timestamp('2013-07-05'), pd.Timestamp('2013-07-07')] 
 
ser.index.isin(time_range) 
 
array([ True, False,  True, False, False, False, False, False, False, False], dtype=bool)