Shubham Rajput
Shubham Rajput

Reputation: 302

Converting column into multi index column

I am new to python, As a result of groupby I got a data frame which looks like this.

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

but I want to convert it into some thing like this.

enter image description here

Tried stack(), unstack(), multi-indexing but didn't succeed. Please help

Upvotes: 2

Views: 3038

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Use, stack, to_frame and T:

temp.stack().to_frame().T

Output:

Year 2018                2017               
     week  mtd  qtd  ytd week  mtd  qtd  ytd
0     200  100  300  400  100  200  345  500

Upvotes: 7

Related Questions