我有一个熊猫数据框,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 方法与浮点数一起使用时,我得到一个类型错误:
In [24]: df_data.index.asof(10.0)
...
TypeError: Cannot compare type 'Timestamp' with type 'float'
我尝试使用datetime,datetime.fromtimestamp等,但无法解决问题。
感谢@joris的深刻评论。
溶液
在将索引从 DateTimeIndex 更改为浮点数(即问题中所述的初始测量后的秒数)之前,您需要确定您希望找到最接近索引的时间(在本例中,我使用一个简单的示例,其中包含一次时间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