将列转换为多索引列

Shu*_*put 2 dataframe python-3.x pandas

我是 python 新手,由于 groupby,我得到了一个看起来像这样的数据框。

temp = pd.DataFrame({'Year' : [2018,2017],
               'week' : [200, 100],
               'mtd' : [100, 200],
               'qtd' : [300, 345],
               'ytd': [400, 500]})
temp.set_index('Year', inplace = True)
print(temp)

      week  mtd  qtd  ytd
Year                     
2018   200  100  300  400
2017   100  200  345  500
Run Code Online (Sandbox Code Playgroud)

但我想把它转换成这样的东西。

在此处输入图片说明

尝试过 stack()、unstack()、多索引但没有成功。请帮忙

Sco*_*ton 6

使用stackto_frameT

temp.stack().to_frame().T
Run Code Online (Sandbox Code Playgroud)

输出:

Year 2018                2017               
     week  mtd  qtd  ytd week  mtd  qtd  ytd
0     200  100  300  400  100  200  345  500
Run Code Online (Sandbox Code Playgroud)