Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transform pandas pivot table to regular dataframe

Tags:

python

pandas

How can I convert a pandas pivot table to a regular dataframe ? For example:

                           amount                                                
categories                  A                B           C  
date         deposit                                                             
2017-01-15   6220140.00    5614354.16        0.00        0.00 
2017-01-16   7384354.00    6247300.22        0.00        0.00 
2017-01-17   6783939.00    10630021.37       0.00        0.00 
2017-01-18   67940.00      4659384.47        0.00        0.00

to a regular datetime such as this:

   date         deposit       A                 B           C                                                                         
0  2017-01-15   6220140.00    5614354.16        0.00        0.00 
1  2017-01-16   7384354.00    6247300.22        0.00        0.00 
2  2017-01-17   6783939.00    10630021.37       0.00        0.00 
3  2017-01-18   67940.00      4659384.47        0.00        0.00
like image 477
DougKruger Avatar asked May 03 '17 09:05

DougKruger


People also ask

Is a pandas pivot table a DataFrame?

pivot_table. Create a spreadsheet-style pivot table as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame.

How do I Unpivot pandas?

In pandas, you can use the melt() function to unpivot a DataFrame – converting it from a wide format to a long format. This function uses the following basic syntax: df_unpivot = pd. melt(df, id_vars='col1', value_vars=['col2', 'col3', ...])


2 Answers

Use droplevel + index name to None + reset_index:

df.columns = df.columns.droplevel(0) #remove amount
df.columns.name = None               #remove categories
df = df.reset_index()                #index to columns

Alternatively use rename_axis:

df.columns = df.columns.droplevel(0)
df = df.reset_index().rename_axis(None, axis=1)

EDIT:

Maybe also help remove [] in parameter values - see this.

like image 119
jezrael Avatar answered Sep 19 '22 06:09

jezrael


df = pd.DataFrame(df.to_records())
like image 40
budfox3 Avatar answered Sep 19 '22 06:09

budfox3