Python Pandas中的datetime.time - datetime.time

7
我可以帮助您进行翻译。以下是需要翻译的内容:

我有一个数据框,其中包含两列datetime.time项目。类似于

   col1                 col2
02:10:00.008209    02:08:38.053145
02:10:00.567054    02:08:38.053145
02:10:00.609842    02:08:38.053145
02:10:00.728153    02:08:38.053145
02:10:02.394408    02:08:38.053145

我该如何生成一列 col3,其中包含 col1 和 col2 的差值?(最好是微秒级别的)?

我搜索了一下,但在这里找不到解决方案。有人知道吗?

谢谢!

3个回答

3

不要使用datetime.time,而要使用timedelta

import pandas as pd
import io
data = """col1                 col2
02:10:00.008209    02:08:38.053145
02:10:00.567054    02:08:38.053145
02:10:00.609842    02:08:38.053145
02:10:00.728153    02:08:38.053145
02:10:02.394408    02:08:38.053145"""
df = pd.read_table(io.BytesIO(data), delim_whitespace=True)
df2 = df.apply(pd.to_timedelta)
diff = df2.col1 - df2.col2

diff.astype("i8")/1e9

输出结果不同时刻不同:

0    81.955064
1    82.513909
2    82.556697
3    82.675008
4    84.341263
dtype: float64

将时间数据框转换为时间差数据框:
df.applymap(time.isoformat).apply(pd.to_timedelta)

2

你确定需要一个由datetime.time对象组成的DataFrame吗?这些对象放在DataFrame中时,几乎无法方便地执行任何操作。

最好是每个列都存储表示总微秒数的整数。

可以使用以下方式将df转换为存储微秒的DataFrame:

In [71]: df2 = df.applymap(lambda x: ((x.hour*60+x.minute)*60+x.second)*10**6+x.microsecond)

In [72]: df2
Out[72]: 
         col1        col2
0  7800008209  7718053145
1  7800567054  7718053145

从那里开始,很容易得到您想要的结果:
In [73]: df2['col1']-df2['col2']
Out[73]: 
0    81955064
1    82513909
dtype: int64

1

pandasdatetime 对象转换为 np.datetime64 对象,它们之间的差异是 np.timedelta64 对象。

考虑以下内容

In [30]: df
Out[30]: 
                       0                          1
0 2014-02-28 13:30:19.926778 2014-02-28 13:30:47.178474
1 2014-02-28 13:30:29.814575 2014-02-28 13:30:51.183349

我可以通过列差来考虑:

 df[0] - df[1]


 Out[31]: 
 0   -00:00:27.251696
 1   -00:00:21.368774
 dtype: timedelta64[ns]

因此,我可以应用timedelta64转换。对于微秒。
(df[0] - df[1]).apply(lambda x : x.astype('timedelta64[us]')) #no actual difference when displayed

或者作为整数的微秒。
(df[0] - df[1]).apply(lambda x : x.astype('timedelta64[us]').astype('int'))

 0   -27251696000
 1   -21368774000
 dtype: int64

编辑: 如@Jeff所建议的那样,最后的表达可以简化为

(df[0] - df[1]).astype('timedelta64[us]')

and

(df[0] - df[1]).astype('timedelta64[us]').astype('int')

对于 pandas >= .13。


1
在 pandas >= 0.13 中,你可以直接执行 df[0]-df[1].astype('timedelta[us]') - Jeff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接