2016-11-26 55 views
3

我有以下形式的時間序列數據幀:如何使用修改後的索引來樞轉熊貓數據框?

rng = pd.date_range('1/1/2013', periods=1000, freq='10min') 
ts = pd.Series(np.random.randn(len(rng)), index=rng) 
ts = ts.to_frame(name=None) 

我需要做兩件事情是:

步驟1:修改索引,讓每天的17:00開始: 00前一天。我做到這一點使用:

ts.index = pd.to_datetime(ts.index.values + np.where((ts.index.time >= datetime.time(17)), pd.offsets.Day(1).nanos, 0)) 

第2步:透視數據幀,這樣的:

ts_ = pd.pivot_table(ts, index=ts.index.date, columns=ts.index.time, values=0) 

我的問題,是,樞數據幀時,熊貓似乎忘記了修改指數我做步1

這是我得到

   00:00:00 00:10:00 00:20:00 ... 23:50:00 
2013-01-10 -1.800381 -0.459226 -0.172929 ... -1.000381 
2013-01-11 -1.258317 -0.973924 0.955224 ... 0.072929 
2013-01-12 -0.834976 0.018793 -0.141608 ... 2.072929 
2013-01-13 -0.131197 0.289998 2.200644 ... 1.589998 
2013-01-14 -0.991653 0.276874 -1.390654 ... -2.090654 

這實際上是期望的結果

   17:00:00 17:10:00 17:20:00 ... 16:50:00 
2013-01-10 -2.800381 1.000226 2.172929 ... 0.172929 
2013-01-11 0.312587 1.003924 2.556624 ... -0.556624 
2013-01-12 2.976834 1.000003 -2.141608 ... -1.141608 
2013-01-13 1.197131 1.333998 -2.999944 ... -1.999944 
2013-01-14 -1.653991 1.278884 -1.390654 ... -4.390654 

編輯 - 澄清注:請注意如何它希望每一天開始於'17:00:00' 在'16結束:50:00' 。

使用Python 2.7

注:通過Nickil Maveli提出的解決方案aproximates答案,但正在發生變化之日起走錯了路。這個想法是,Day_t = '17:00'開始於Day_t-1。現在,解決方案正在執行Day_t =於'17:00'開始於Day_t。

回答

2

所以,我需要畫一些圖片,讓here它們分別是:

# Step 1: 

df1 = df.ix[:,   :'16:59'] # http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html 
df2 = df.ix[:, '17:00' :  ] 

# Step 2: 

df3 = df2.shift(periods = 1) # http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html 

# Step 3: 

df4 = pandas.concat([df3, df1], axis = 1) # http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html 
2

這裏您確實不需要使用np.where,因爲您僅僅對1個參數執行過濾。此外,else部分爲0.因此,此步驟後得到的索引絕對沒有減少。

相反,你必須,這樣做:

1.Build了一個布爾口罩過濾日期時間增加,其hour屬性大於或等於17的,每天的偏移:

arr = ts.index 
idx = arr[arr.hour >= 17] + pd.offsets.Day(1) 

2 。基於修改索引的索引:

ts_clip = ts.reindex(idx) 

3。執行pivot操作:

pd.pivot_table(ts_clip, index=ts_clip.index.date, columns=ts_clip.index.time, values=0) 

enter image description here


編輯

ts_clip = ts.iloc[np.argwhere(ts.index.hour.__eq__(17)).ravel()[0]:] 
ts_clip_shift = ts_clip.tshift(-17, freq='H') 
df = pd.pivot_table(ts_clip_shift, index=(ts_clip_shift.index + pd.offsets.Day(n=1)), 
        columns=ts_clip_shift.index.time, values=0) 
df.columns= ts_clip.iloc[:len(df.columns)].index.time 

檢查DF特點:

df.info() 
<class 'pandas.core.frame.DataFrame'> 
Index: 7 entries, 2013-01-02 to 2013-01-08 
Columns: 144 entries, 17:00:00 to 16:50:00 
dtypes: float64(144) 
memory usage: 7.9+ KB 
+1

你提出「印章」的數據,其中的每一天去從'17解決辦法:00' 到'23:50" 。我需要每一天從'17:00'到'16; 50'。 – hernanavella

+0

*請參閱編輯*。更正。 –

+1

我發現了這個問題。在某個時候,程序正在錯誤地改變日子。這個想法是,Day_t = '17:00'開始於Day_t-1。現在,解決方案正在執行Day_t =於'17:00'開始於Day_t。我加了一張紙條。 – hernanavella