2014-02-28 41 views
7

我有一個數據幀,其中包含兩列datetime.time項目。像python pandas 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之間的差異? (最好是微秒)?

我周圍搜索,但我找不到解決方案在這裏。有人知道嗎?

謝謝!

回答

1

你確定你想要一個DataFrame的datetime.time對象嗎?幾乎沒有一種操作可以方便地在這些人身上執行,尤其是在包裝在DataFrame中時。

讓每列存儲一個表示總微秒數的整數可能會更好。

可以轉換df到一個數據幀存儲微秒這樣的:

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 
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 

到時候數據幀轉換爲timedelta數據幀:

df.applymap(time.isoformat).apply(pd.to_timedelta) 
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 

編輯: 作爲suggessted由@Jeff,最後的表達式可以縮短

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

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

大熊貓> = .13。

+1

熊貓> = 0.13,你可以做''df [0] -df [1] .astype('timedelta [us]')'' – Jeff

相關問題