Pandas Format Pivot Table

I came across a problem in formatting a pivot table created by Pandas. So I made a matrix table between two columns (A, B) from my original data using Pandas.pivot_table with A as column and B as index.

>> df = PD.read_excel("data.xls")
>> table = PD.pivot_table(df,index=["B"],
    values='Count',columns=["A"],aggfunc=[NUM.sum],
    fill_value=0,margins=True,dropna= True)
>> table 

      

It returns as:

      sum
  A     1  2  3  All
  B 
  1     23 52  0  75
  2     16 35 12  65
  3     56  0  0  56
All     95 87 12 196

      

And I hope to have this format:

                A      All_B
            1   2   3   
    1      23  52   0     75
B   2      16  35  12     65
    3      56   0   0     56
All_A      95  87  12    196

      

How should I do it? Thank you very much forward.

+3


source to share


1 answer


The table returned pd.pivot_table

is very easy to work with (it is a sibling index / column) and usually does NOT require further format processing. But if you insist on changing the format to the one you mentioned in the post, you need to build a multi-level index / column using pd.MultiIndex

. Here's an example on how to do this.

Before manipulation

import pandas as pd
import numpy as np

np.random.seed(0)
a = np.random.randint(1, 4, 100)
b = np.random.randint(1, 4, 100)
df = pd.DataFrame(dict(A=a,B=b,Val=np.random.randint(1,100,100)))
table = pd.pivot_table(df, index='A', columns='B', values='Val', aggfunc=sum, fill_value=0, margins=True)
print(table)


B       1     2     3   All
A                          
1     454   649   770  1873
2     628   576   467  1671
3     376   247   481  1104
All  1458  1472  1718  4648    

      



After:

multi_level_column = pd.MultiIndex.from_arrays([['A', 'A', 'A', 'All_B'], [1,2,3,'']])
multi_level_index = pd.MultiIndex.from_arrays([['B', 'B', 'B', 'All_A'], [1,2,3,'']])
table.index = multi_level_index
table.columns = multi_level_column
print(table)

            A             All_B
            1     2     3      
B     1   454   649   770  1873
      2   628   576   467  1671
      3   376   247   481  1104
All_A    1458  1472  1718  4648    

      

+1


source







All Articles