将DatetimeIndex转换为Timedelta索引 [英] Converting DatetimeIndex to Timedelta index
本文介绍了将DatetimeIndex转换为Timedelta索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出:
ts = pd.to_datetime(['2014-01-08 08:00:42',
'2014-01-08 08:01:00',
'2014-01-08 08:01:12'])
是否存在规定的方法来获取每个元素之间的时间增量(最好是total_seconds
属性)?
Is there a prescribed way to get a result that is the timedelta (preferably total_seconds
attribute) between each element?
我现在所拥有的似乎太冗长了:
What I have now seems overly verbose:
pd.Index((pd.Series(ts) - pd.Series(ts).shift())).total_seconds()
# Float64Index([nan, 18.0, 12.0], dtype='float64')
我不太在意最终的数据结构类型,无论是列表,索引还是序列.
I don't really care about the resulting data structure type, be it a list, Index, or Series.
推荐答案
您可以通过这种方式使用np.diff
.
You can use np.diff
in this way.
np.diff(ts.values).astype(int) / 1E9
array([ 18., 12.])
或
np.append(np.nan, np.diff(ts.values).astype(int) / 1E9)
array([ nan, 18., 12.])
这篇关于将DatetimeIndex转换为Timedelta索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文