Creating non-numeric pivot tables with Python Pandas (recipe two)

Viva Enrico Bergamini

As Enrico has written in his recipe one:

If you ever tried to pivot a table containing non-numeric values, you have surely been struggling with any spreadsheet app to do it easily.

He has proposed a recipe to do it, using Python pandas and pivot_table function.

In my recipe I will use pandas unstack. It “pivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels”.

The goal of Enrico is to change the original table as the image below:

The code to do all is the one below:

from pandas import *
dataFrame=read_csv('enri.csv')
dataFrame.set_index(['id','key'],inplace=True)
df=dataFrame.unstack()
df.reset_index(inplace=True)

And yon can see all in action in the below gist.

It’s only a reshape matter!