python pandas TypeError:无法比较“Timestamp”类型和“float”类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26918045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python pandas TypeError: Cannot compare type 'Timestamp' with type 'float'
提问by dhltp
I have a pandas data frame, df_data, want to use the pandas index.asof() method to find the nearest row to a specified time. The times I have are in seconds (type = float64) (see below).
我有一个pandas 数据框,df_data想使用pandas index.asof() 方法来查找距指定时间最近的行。我的时间以秒为单位(type = float64)(见下文)。
Originally, the index was made to be a DateTimeIndex:
最初,索引是一个 DateTimeIndex:
In [12]: df_data.index = pd.to_datetime(df_data.index, coerce=True)
df_data.index.dtype
Out[12]: dtype('<M8[ns]')
Then, I changed the index to be in seconds from the initial time:
然后,我将索引从初始时间更改为以秒为单位:
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')
But when I try to use the asof method with a float, I get a TypeError:
但是当我尝试使用带有浮点数的 asof 方法时,我得到了一个 TypeError:
In [24]: df_data.index.asof(10.0)
...
TypeError: Cannot compare type 'Timestamp' with type 'float'
I have tried to use datetime, datetime.fromtimestamp, etc., but haven't been able to resolve the issue.
我曾尝试使用 datetime、datetime.fromtimestamp 等,但一直无法解决问题。
采纳答案by dhltp
Thanks to @joris for the insightful comment.
感谢@joris 的有见地的评论。
SOLUTION
解决方案
Before changing the index from DateTimeIndex to a float (i.e., seconds from initial measurement as described in the question), you need to identify the times (in this case I use a simple example with one time time_float) at which you'd like to find the nearest index. Then, those datetime indices can be transformed to float indices:
在将索引从 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
Now, after the overall conversion of the index (given above) to seconds from the initial time, I can refer to the index closest to time_float, which is time_index:
现在,在将索引(上面给出的)从初始时间整体转换为秒后,我可以参考最接近 的索引time_float,即time_index:
In [24]: df_data.ix[time_index,0]
Out[24]: 0.00075450129999999997

