2013-07-26 94 views
1

我正在尋找使用日期時間索引在熊貓數據框中的6小時的差距,我想創建一個列表與日期時間對象剛剛在使用列表理解這樣的差距之後:熊貓日期時間索引列表理解

starttimes = [x for i, x in enumerate(data.index) if ((x - x[i-1]).seconds/3600.0) > 6 ] 

,但我得到以下類型的錯誤:

TypeError: 'Timestamp' object does not support indexing 

的枚舉(data.index)之後出現的錯誤,但我不知道爲什麼我收到這個錯誤,因爲我可以做的:

(data.index[0] - data.index[1]).seconds/3600.0 > 6 

蠻好的,輸出是真的。

我也試過這種方式,獲得了不同類型的錯誤:

starttime = [x for i, x in enumerate(WaterTest) if ((x.index - x.index[i-1]).seconds/3600.0) > 6 ] 

TypeError: 'builtin_function_or_method' object has no attribute '__getitem__' 

有沒有一種方法可以輕鬆地做到這一點?我必須在我的代碼中經常使用這些語句,並且能夠以類似於此的方式編寫它們會很好。

回答

3

在迭代中,DatetimeIndex它的值轉換爲時間戳

In [26]: index = pd.DatetimeIndex(['20130101 12:00:00','20130101 18:01:01','20130102 9:00:00','20130102 23:00:05']) 

In [27]: index 
Out[27]: 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2013-01-01 12:00:00, ..., 2013-01-02 23:00:05] 
Length: 4, Freq: None, Timezone: None 

In [28]: for x in index: 
    ....:  print type(x) 
    ....:  
<class 'pandas.tslib.Timestamp'> 
<class 'pandas.tslib.Timestamp'> 
<class 'pandas.tslib.Timestamp'> 
<class 'pandas.tslib.Timestamp'> 

但有一個更簡單的方法做你正在做的事情

時間 - shifted_time = timedelta

In [29]: td = index.to_series().diff() 

In [30]: td 
Out[30]: 
2013-01-01 12:00:00  NaT 
2013-01-01 18:01:01 06:01:01 
2013-01-02 09:00:00 14:58:59 
2013-01-02 23:00:05 14:00:05 
dtype: timedelta64[ns] 

這在numpy> = 1.7中是有效的(參見這裏可以做的其他操作以及如果numpy < 1.7如何操作):http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas

差在6個小時爲單位

In [31]: td.apply(lambda x: x/np.timedelta64(6,'h')) 
Out[31]: 
2013-01-01 12:00:00   NaN 
2013-01-01 18:01:01 1.002824 
2013-01-02 09:00:00 2.497176 
2013-01-02 23:00:05 2.333565 
dtype: float64 
+0

我numpy的版本是1.7.1,但因爲你沒有以上我需要抓住一個較新的版本,我不能使用爲.diff()或。適用於TD? – pbreach

+0

你能顯示你的代碼嗎? – Jeff

+0

忘記導入日期時間,但它現在工作,速度很快!謝謝 – pbreach

相關問題