[英]python pandas datetime.time - datetime.time
我有一個數據框,其中包含兩列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之間的差異? (優選在幾微秒內)?
我四處搜索,但我找不到解決方案。 有人知道嗎?
謝謝!
不要使用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
要將時間數據幀轉換為timedelta數據幀:
df.applymap(time.isoformat).apply(pd.to_timedelta)
您確定要一個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
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
編輯:正如@Jeff所建議的那樣,最后的表達式可以縮短為
(df[0] - df[1]).astype('timedelta64[us]')
和
(df[0] - df[1]).astype('timedelta64[us]').astype('int')
對於pandas> = .13。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.