2017-05-26 29 views
1

我有一個熊貓DF,看起來像這樣:如何將pandas datatimeindex轉換爲每日兩次的頻率?

  Open_fut Close_fut 
Date       
2017-05-12 20873.0 20850.0 
2017-05-11 20887.0 20869.0 
2017-05-10 20891.0 20888.0 
2017-05-09 20943.0 20886.0 
2017-05-08 21001.0 20943.0 

我的日期datetime64[ns],在其他列float64

如何讓我的時間系列以Open_fut來到2017-05-12 09:30:00Close_fut2017-05-12 15:30:00等等每一天?

編輯:

理想情況下,新的DF是這樣的:

    fut 
Date       
2017-05-12 09:30:00 20873.0 
2017-05-12 15:30:00 20850.0 
. 
. 

回答

3

看來你需要MultiIndex.from_arrays與添加timesto_timedelta

time1 = '09:30:00' 
time2 = '15:30:00' 

df.index = pd.MultiIndex.from_arrays([df.index + pd.to_timedelta(time1), 
             df.index + pd.to_timedelta(time2)], 
             names=['date1','date2']) 
print (df) 
             Open_fut Close_fut 
date1    date2         
2017-05-12 09:30:00 2017-05-12 15:30:00 20873.0 20850.0 
2017-05-11 09:30:00 2017-05-11 15:30:00 20887.0 20869.0 
2017-05-10 09:30:00 2017-05-10 15:30:00 20891.0 20888.0 
2017-05-09 09:30:00 2017-05-09 15:30:00 20943.0 20886.0 
2017-05-08 09:30:00 2017-05-08 15:30:00 21001.0 20943.0 

對於你的輸出解決方案類似,只用lreshape進行重塑+ set_index + sort_index

time1 = '09:30:00' 
time2 = '15:30:00' 

df['date1'] = df.index + pd.to_timedelta(time1) 
df['date2'] = df.index + pd.to_timedelta(time2)         
df = pd.lreshape(df, {'date':['date1', 'date2'], 'fut':['Open_fut', 'Close_fut']}) 
df = df.set_index('date').sort_index()    
print (df) 
         fut 
date       
2017-05-08 09:30:00 21001.0 
2017-05-08 15:30:00 20943.0 
2017-05-09 09:30:00 20943.0 
2017-05-09 15:30:00 20886.0 
2017-05-10 09:30:00 20891.0 
2017-05-10 15:30:00 20888.0 
2017-05-11 09:30:00 20887.0 
2017-05-11 15:30:00 20869.0 
2017-05-12 09:30:00 20873.0 
2017-05-12 15:30:00 20850.0 

編輯:

lreshape現在無證的,但有可能在未來會被刪除(with pd.wide_to_long too)。

可能的解決方案是將所有3個功能合併到一個 - 也許melt,但現在它不實現。也許在一些新版熊貓中。然後我的答案將被更新。

+0

請參閱我的編輯。 – cJc

+0

檢查我最後的編輯。 – jezrael

+1

我喜歡你的'lreshape'解決方案;-)! – MaxU