将Pandas TimeDelta转换为整数 [英] Convert Pandas TimeDelta to integer
问题描述
假设我有一个包含TimeDelta数据的熊猫系列. 实际上,它是通过将DateTimeIndex与自身的偏移版本进行比较而生成的,因此给出了连续时间戳之间的差异.
Suppose I have a Pandas Series that contains TimeDelta data. In fact it has been generated by taking the difference of a DateTimeIndex with a shifted version of itself, hence giving the delta between consecutive timestamps.
看起来像
timestamp
2015-02-01 00:00:04 00:00:04
2015-02-01 00:00:08 00:00:04
2015-02-01 00:00:12 00:00:04
....
Name: timestamp, dtype: timedelta64[ns]
这些值显然是numpy.timedelta64,但我需要将它们设置为几秒钟. 与此相关的问题也有类似的问题,但我尚未看到与Pandas 0.16.1有关的答案.
The values are obviously numpy.timedelta64 but I need to get them into seconds. There have been similar questions asked relating to this but no answers I have seen yet that deals with Pandas 0.16.1.
我尝试过的是:
ts.apply(lambda x: x.seconds)
哪个错误
AttributeError:"numpy.timedelta64"对象没有属性"seconds"
AttributeError: 'numpy.timedelta64' object has no attribute 'seconds'
然后尝试
numpy.int64(ts)
但是,这给了我一个数组.现在我知道我可以将其转换为Series了,但是在一个Pandas调用或映射函数中没有其他方法可以做到这一点吗?
But that gives me an array. Now I know I can convert that back into a Series but is there not another way to do this in one Pandas call or mapping function?
推荐答案
以下内容对我有用:
In [24]:
t="""index,timestamp
2015-02-01 00:00:04,00:00:04
2015-02-01 00:00:08,00:00:04
2015-02-01 00:00:12,00:00:04"""
s = pd.read_csv(io.StringIO(t),parse_dates=[0,1], squeeze=True, index_col=[0])
In [26]:
s.dt.second
Out[26]:
index
2015-02-01 00:00:04 4
2015-02-01 00:00:08 4
2015-02-01 00:00:12 4
dtype: int64
datetime dtype值具有 dt
访问器,您可以在其中访问seconds属性.
datetime dtype values have a dt
accessor where you can access the seconds attribute.
这篇关于将Pandas TimeDelta转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!