2013-03-01 91 views
12

的前值我有一個數據幀的大熊貓與日期時間指數得到大熊貓日期時間指數

Date 
2013-02-22 00:00:00+00:00 0.280001 
2013-02-25 00:00:00+00:00 0.109999 
2013-02-26 00:00:00+00:00 -0.150000 
2013-02-27 00:00:00+00:00 0.130001 
2013-02-28 00:00:00+00:00 0.139999 
Name: MOM12 

,並要評估定日期時間指數的前三個值。

date = "2013-02-27 00:00:00+00:00" 
df.ix[date] 

我搜索了這一點,但因爲我的指標是約會,我不能做

df.ix[int-1] 
+0

你有一個索引的每一天,還是有一些跳過天? – 2013-03-01 16:50:34

+0

例如,有一些跳過的日子,週末和假期。 – trbck 2013-03-01 17:51:53

+0

這個問題可以幫助你:[切割熊貓時間序列日期+/- 2個工作日](http://stackoverflow.com/questions/14092339/slice-pandas-timeseries-on-date-2-business-days) – 2013-03-01 20:05:47

回答

12

這裏有一種方法通過get_loc做到這一點,首先搶索引鍵的整數位置:

In [15]: t = pd.Timestamp("2013-02-27 00:00:00+00:00") 

In [16]: df1.index.get_loc(t) 
Out[16]: 3 

然後你就可以使用iloc(獲取整數位置,或切片由整數位置):

In [17]: loc = df1.index.get_loc(t) 

In [18]: df.iloc[loc - 1] 
Out[18]: 
Date 2013-02-26 00:00:00 
         -0.15 
Name: 2, Dtype: object 

In [19]: df1.iloc[slice(max(0, loc-3), min(loc, len(df)))] 
     # the min and max feel slightly hacky (!) but needed incase it's within top or bottom 3 
Out[19]:       
Date      
2013-02-22 0.280001 
2013-02-25 0.109999 
2013-02-26 -0.150000 

indexing section of the docs


我不太清楚你如何設置你的數據幀,但看起來並不像一個日期時間指數給我。這是我如何得到數據幀(帶時間戳指數):

In [11]: df = pd.read_clipboard(sep='\s\s+', header=None, parse_dates=[0], names=['Date', None]) 

In [12]: df 
Out[12]: 
       Date   
0 2013-02-22 00:00:00 0.280001 
1 2013-02-25 00:00:00 0.109999 
2 2013-02-26 00:00:00 -0.150000 
3 2013-02-27 00:00:00 0.130001 
4 2013-02-28 00:00:00 0.139999 

In [13]: df1 = df.set_index('Date') 

In [14]: df1 
Out[14]:     
Date     
2013-02-22 0.280001 
2013-02-25 0.109999 
2013-02-26 -0.150000 
2013-02-27 0.130001 
2013-02-28 0.139999 
+0

對irow的支持已被棄用:http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.irow.html,應該使用iloc – user2413548 2017-12-17 22:27:12

+0

@ user2413548謝謝,我需要寫一個腳本來通過所有這些答案! – 2017-12-18 00:26:12