2016-05-19 69 views
1

我有時間戳列表:如何生成從此處,參考產生以前的時間戳每個TimeDelta一個時間戳列TimedeltaIndex

Timestamp 

2015-10-01 00:00:08          
2015-10-01 00:00:18          
2015-10-01 00:00:28          
2015-10-01 00:00:38          
2015-10-01 00:00:48          
2015-10-01 00:00:58          
2015-10-01 00:01:08          
2015-10-01 00:01:17 

,我想生成時間戳,其中TimeDeltas每個TimeDelta值取基準從以前的時間戳是這樣的:

Timestamp    TimeDelta 

2015-10-01 00:00:08  00:00:00.000       
2015-10-01 00:00:18  00:00:10.000      
2015-10-01 00:00:28  00:00:10.000      
2015-10-01 00:00:38  00:00:10.000      
2015-10-01 00:00:48  00:00:10.000      
2015-10-01 00:00:58  00:00:10.000      
2015-10-01 00:01:08  00:00:10.000      
2015-10-01 00:01:17  00:00:09.000 

但相反我得到這個:

Timestamp    TimeDelta 

2015-10-01 00:00:08  00:00:00.000       
2015-10-01 00:00:18  00:00:10.000      
2015-10-01 00:00:28  00:00:20.000      
2015-10-01 00:00:38  00:00:30.000      
2015-10-01 00:00:48  00:00:40.000      
2015-10-01 00:00:58  00:00:50.000      
2015-10-01 00:01:08  00:01:00.000      
2015-10-01 00:01:17  00:01:09.000 

我用下面的代碼:

df['TimeDelta'] = pd.TimedeltaIndex(df['Timestamp']) 

謝謝!

回答

1

使用diff法計算相鄰行的區別:

df['TimeDelta'] = df['Timestamp'].diff().fillna(0) 

import pandas as pd 

df = pd.DataFrame({'Timestamp': ['2015-10-01 00:00:08', '2015-10-01 00:00:18', 
    '2015-10-01 00:00:28', '2015-10-01 00:00:38', '2015-10-01 00:00:48', 
    '2015-10-01 00:00:58', '2015-10-01 00:01:08', '2015-10-01 00:01:17']}) 
df['Timestamp'] = pd.to_datetime(df['Timestamp']) 
df['TimeDelta'] = df['Timestamp'].diff().fillna(0) 
print(df) 

產量

  Timestamp TimeDelta 
0 2015-10-01 00:00:08 00:00:00 
1 2015-10-01 00:00:18 00:00:10 
2 2015-10-01 00:00:28 00:00:10 
3 2015-10-01 00:00:38 00:00:10 
4 2015-10-01 00:00:48 00:00:10 
5 2015-10-01 00:00:58 00:00:10 
6 2015-10-01 00:01:08 00:00:10 
7 2015-10-01 00:01:17 00:00:09 
+0

嘿感謝!我試過了,但不幸的是它告訴我'.diff()'已被棄用,並告訴我使用[.difference](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex .difference.html?highlight = difference)。我試過'df ['TimeDelta'] = pd.TimedeltaIndex(df ['date'] - df ['date']。shift(1))'及其工作! – cookiedookie

+0

不推薦使用'DatetimeIndex.diff'方法。但是'Series.diff'方法不是。由於'df ['Timestamp']'是一系列(dtype'datetime64 [ns]'),因此使用'df ['Timestamp']。diff()'應該沒有問題。 – unutbu

+0

你是對的!它確實有用!我犯了一個錯誤,我之前使用了以下內容:'df ['TimeDelta'] = pd.TimedeltaIndex(df ['Timestamp'])。difference()。fillna(0)'謝謝你的幫助! – cookiedookie