重命名多级dateTime索引Pandas

时间:2018-03-08 22:20:19

标签: python pandas

我有一个看起来像这样的数据框

                     Sale    Purchase
date date date date  100       3
2018  2    1    1    200       6 
2018  1    2    3    150       8
2017  12   1    1    100       1
2017  11   2    2    50        2

相反,我希望它可能是

                           Sale    Purchase
Year Month Week Dayofweek  100       3
2018  2    1    1          200       6 
2018  1    2    3          150       8
2017  12   1    1          100       1
2017  11   2    2          50        2

我试过df_monthly.MultiIndex.rename("Year","Month","Week","Dayofweek") 但我得到错误AttributeError:'DataFrame'对象没有属性'MultiIndex'。有没有其他方法来重命名这些索引?感谢

我也试过df_monthly = pd.MultiIndex.rename(df_monthly.index,['年','月','周','星期'',[0,1,2,3])似乎也无效。

2 个答案:

答案 0 :(得分:0)

使用

// results is a div holding the results. 
// As soon as the search returns and the results are 
// added (even before the keyboard is gone) i run the 
// code below and once the keyboard is gone things scroll 
// properly. It's basically a hack to get the browser to 
// recalculate positioning and rendering. class 'absolute'
// just sets the position to absolute from it's default 'relative'.

results.addClass('absolute');
// Force browser to assume there's upcoming rendering to do
results.element.clientHeight;
// remove class
results.removeClass('absolute');

df_monthly.index.set_names('Year', level=0)

正如您可以从错误中推断出的那样,df.index属性存储了MultiIndex类的实例。

答案 1 :(得分:0)

经过多次搜索和反复试验,解决方案如下

df_monthly.index.names=['Year','Month','Week','Day of Week']