将 Pandas TimeDelta 转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30199774/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:20:18  来源:igfitidea点击:

Convert Pandas TimeDelta to integer

pythonpandas

提问by Will

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.

假设我有一个包含 TimeDelta 数据的 Pandas 系列。事实上,它是通过将 DateTimeIndex 与它自身的移位版本的差值而生成的,因此给出了连续时间戳之间的增量。

It looks something like

它看起来像

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]

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.

这些值显然是 numpy.timedelta64 但我需要把它们变成几秒钟。已经提出了与此相关的类似问题,但我还没有看到涉及 Pandas 0.16.1 的答案。

What I've tried is:

我试过的是:

ts.apply(lambda x: x.seconds)

Which gives an error of

这给出了一个错误

AttributeError: 'numpy.timedelta64' object has no attribute 'seconds'

AttributeError: 'numpy.timedelta64' 对象没有属性 'seconds'

Then tried

然后试过

numpy.int64(ts)

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?

但这给了我一个数组。现在我知道我可以将它转换回系列,但是在 Pandas 调用或映射函数中没有另一种方法可以做到这一点吗?

采纳答案by EdChum

The following worked for me:

以下对我有用:

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 values have a dtaccessor where you can access the seconds attribute.

datetime dtype 值有一个dt访问器,您可以在其中访问 seconds 属性。