New2coding
New2coding

Reputation: 717

Reshaping pandas dataframe with unstack()

I am trying to reshape pandas DataFrame so that one of the columns would be unstacked to 'broader'. Once I proceed with unstack() new column levels occure but I seem to be unable to re-arrange the headers the way I want.

Firstly, I have following df:

from pandas import *

fList = [['Packs', 'Brablik', 'Holesovice', '2017', 100],
         ['Decorations', 'Drapp-design', 'Holesovice', '2017', 150],
         ['Decorations', 'Klapetkovi', 'Holesovice', '2017', 200],
         ['Decorations', 'Lezecké dárky', 'Fler', '2017', 100],
         ['Decorations', 'PP', 'Other', '2017', 350],
         ['Decorations', 'Pavlimila', 'Akce', '2017', 20],
         ['Decorations', 'Pavlimila', 'Holesovice', '2017', 50],
         ['Decorations', 'Wiccare', 'Holesovice', '2017', 70],
         ['Toys', 'Klára Vágnerová', 'Holesovice', '2017', 100],
         ['Toys', 'Lucie Polonyiová', 'Holesovice', '2017', 80],
         ['Dresses', 'PP', 'Other', '2018', 200]]

df = DataFrame(fList, columns = ['Section', 'Seller', 'Store', 'Selected_period', 'Total_pieces'])

This produces: enter image description here

Consequently I reshape it like:

df = df.set_index(['Section', 'Seller', 'Store', 'Selected_period']).unstack(level = -1)
df = df.fillna(0)
df.columns = df.columns.droplevel(0)

That outputs:

enter image description here

However, I would like to have just following columns in the final dataframe: Section, Seller, Store, 2017, 2018. I still fail to re-arrange it so that I would get the output I want, despite I tried to adopt solutions posted here and here and here. Any suggestions?

Upvotes: 1

Views: 752

Answers (1)

foglerit
foglerit

Reputation: 8279

If I understand correctly, you seem to just be missing a reset_index() call. Try this:

df = df.set_index(['Section', 'Seller', 'Store', 'Selected_period']).unstack(level = -1).fillna(0)
df.columns = df.columns.droplevel(0).rename('')
df = df.reset_index()

enter image description here

Upvotes: 3

Related Questions