pandas pivot table to data frame [duplicate]
After pivoting, convert the dataframe to records and then back to dataframe:
flattened = pd.DataFrame(pivoted.to_records())# subject date ('pills', 250) ('pills', 500) ('pills', 1000)#0 1 10/10/2012 4.0 NaN NaN#1 1 10/11/2012 4.0 NaN NaN#2 1 10/12/2012 NaN 2.0 NaN#3 2 1/6/2014 NaN NaN 1.0#4 2 1/7/2014 1.0 1.0 NaN#5 2 1/8/2014 3.0 NaN NaN
You can now "repair" the column names, if you want:
flattened.columns = [hdr.replace("('pills', ", "strength.").replace(")", "") \ for hdr in flattened.columns]flattened# subject date strength.250 strength.500 strength.1000#0 1 10/10/2012 4.0 NaN NaN#1 1 10/11/2012 4.0 NaN NaN#2 1 10/12/2012 NaN 2.0 NaN#3 2 1/6/2014 NaN NaN 1.0#4 2 1/7/2014 1.0 1.0 NaN#5 2 1/8/2014 3.0 NaN NaN
It's awkward, but it works.