计算两行之间的时差 [英] Calculating time difference between two rows
本文介绍了计算两行之间的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用shift()
计算两行之间的时间差,但出现意外错误.我可能缺少明显的东西
I'm trying to calculate the time difference between two rows using shift()
, but I get an unexpected error. I may be missing something obvious
df['Delta'] = (df.index - df.index.shift(1))
此语句产生一个ValueError: Cannot shift with no offset
.我想念什么?
This statement produces a ValueError: Cannot shift with no offset
. What am I missing?
推荐答案
两件事:
- 如果您有DatetimeIndex,则
shift
会在一段时间内移动数据.如果索引没有频率,则必须使用freq
关键字将其提供给shift方法(例如freq='s'
将数据移动一秒钟) - 您不能像这样减去两个索引对象,因为这会给您带来差异设置操作:
- If you have a DatetimeIndex, the
shift
shifts your data with a period of time. If your index has no frequency, you have to provide that to the shift method with thefreq
keyword (egfreq='s'
to shift the data one second) - You cannot substract two index objects like that, as this gives you a difference set operation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#set-operations-on-index-objects
如果只希望索引中两个连续值之间的差,则可以使用diff
方法(对于Series,比移位和减法容易一些):
If you just want the difference between two consecutive values in the index, you can use the diff
method (of a Series, a bit easier than shift and substract):
df['index_col'] = df.index
df['Delta'] = df['index_col'].diff()
这篇关于计算两行之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文