我有一个数据帧,其中包含两列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
如何生成col1和col2的区别所在的col3?(最好以微秒为单位)?
我到处找,但我在这里找不到解决方案。有人知道吗?
谢谢!
发布于 2014-02-28 12:41:43
不要使用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)
发布于 2014-02-28 11:59:49
您确定需要datetime.time
对象的DataFrame吗?几乎没有什么操作可以方便地对这些人执行,尤其是在包装在DataFrame中时。
让每一列存储一个表示总微秒数的int可能更好。
您可以将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
发布于 2014-02-28 12:41:57
pandas
将datetime
对象转换为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
EDIT:根据@Jeff的建议,最后的表达式可以缩短为
(df[0] - df[1]).astype('timedelta64[us]')
和
(df[0] - df[1]).astype('timedelta64[us]').astype('int')
为熊猫>= .13。
https://stackoverflow.com/questions/22093962
复制相似问题