如何将 pandas datetimeindex 设为每天两次?

How do I make a pandas datatimeindex into twice daily frequency?

我有一个 pandas df 看起来像这样:

           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_fut 出现在 2017-05-12 15:30:00 等等?

编辑:

理想情况下,新的 df 应该是这样的:

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

看来你需要MultiIndex.from_arrays with adding times by 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 for reshaping + 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 is now undocumented, but is possible in future will by removed (with pd.wide_to_long too)。

可能的解决方案是将所有 3 个功能合并为一个 - 也许 melt,但现在尚未实施。也许在 pandas 的某些新版本中。然后我的回答会更新。