Python Pandas:是否可以在多索引数据帧中将date Object转换为DateTimeIndex?

时间:2018-03-27 05:56:10

标签: python pandas

                       open      high       low     close    volume
Ticker  date
NAVER   2008-11-28  185724.0  192776.0  177887.0  191993.0  399179.0
        2008-12-01  191209.0  191993.0  178671.0  178671.0  258409.0
SAMSUNG 2008-11-28  185724.0  192776.0  177887.0  191993.0  399179.0
        2008-12-01  191209.0  191993.0  178671.0  178671.0  258409.0
        2008-12-02  156729.0  174753.0  156729.0  169267.0  296473.0

我曾尝试过,

data_dfs.index = data_dfs.index.set_levels([data_dfs.index.levels[:-1], pd.to_datetime(data_dfs.index.levels[-1])])

它有效,但问题是它删除索引名称' Ticker' ....

所以,我尝试data_dfs = data_dfs.rename_axis(['Ticker', 'date'], axis=1),但它没有将索引名称设置为' Ticker' ...

我该如何处理?

1 个答案:

答案 0 :(得分:1)

我认为您可以将Heroku setup times connections at 55 seconds与参数level=1一起使用,并将值用于set_levels

mux = pd.MultiIndex.from_product([['NAVER'], ['2018-11-28','2018-12-01','2018-12-02']], 
                                 names=['Ticker', 'date'])
df = pd.DataFrame({'open':[1,2,3]}, 
                  index=mux)

df.index = df.index.set_levels(pd.to_datetime(df.index.get_level_values(1)), level=1)
print(df)
                   open
Ticker date            
NAVER  2018-11-28     1
       2018-12-01     2
       2018-12-02     3

print(df.index.get_level_values(1))
DatetimeIndex(['2018-11-28', '2018-12-01', '2018-12-02'],
dtype='datetime64[ns]', name='date', freq=None)