Skip to main content
 首页 » 编程设计

python Pandas TypeError : Cannot compare type 'Timestamp' with type 'float'

2025年05月04日9yyy_WW

我有一个 pandas 数据框,df_data,想使用 pandas index.asof() 方法找到离指定时间最近的行。我的时间以秒为单位(类型 = float64)(见下文)。

最初,索引是一个 DateTimeIndex:

In [12]: df_data.index = pd.to_datetime(df_data.index, coerce=True)  
         df_data.index.dtype 
Out[12]: dtype('<M8[ns]') 

然后,我将索引更改为从初始时间开始以秒为单位:

In [22]: ## Convert the index from DateTimeIndex to a float64  
         ## that is the number of seconds from the initial measurement 
         df_data.index = (df_data.index - df_data.index[0])/np.timedelta64(1,'s') 
In [23]: df_data.index.dtype 
Out[23]: dtype('float64') 

但是当我尝试将 asof 方法与 float 一起使用时,我得到一个 TypeError:

In [24]: df_data.index.asof(10.0) 
... 
TypeError: Cannot compare type 'Timestamp' with type 'float' 

我尝试过使用 datetime、datetime.fromtimestamp 等,但未能解决问题。

请您参考如下方法:

感谢@joris 富有洞察力的评论。

解决方案

在将索引从 DateTimeIndex 更改为 float 之前(即,从问题中描述的初始测量开始的秒数),您需要确定时间(在这种情况下,我使用一个简单的示例,一次 time_float) 你想在其中找到最近的索引。然后,可以将这些日期时间索引转换为浮点索引:

In [21]: time_float = 10.0 
         time_td = df_data.index[0]+ datetime.timedelta(0,time_float) 
         ## convert from the DateTimeIndex type to time from start in seconds as type float64 
         time_index = (df_data.index.asof(time_td) - df_data.index[0]).total_seconds() 
         time_index 
Out[21]: 9.86296 

现在,在将索引(上面给出的)从初始时间整体转换为秒之后,我可以引用最接近time_float的索引,即time_index :

In [24]: df_data.ix[time_index,0] 
Out[24]: 0.00075450129999999997