看來你需要MultiIndex.from_arrays
與添加times
由to_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
,但現在它不實現。也許在一些新版熊貓中。然後我的答案將被更新。
請參閱我的編輯。 – cJc
檢查我最後的編輯。 – jezrael
我喜歡你的'lreshape'解決方案;-)! – MaxU