Home > Blockchain >  Cutomise the ordering of columns in pivot table after .sort_index(level=1, axis=1)
Cutomise the ordering of columns in pivot table after .sort_index(level=1, axis=1)

Time:01-18

Dataframe df1

    TYPE  WEEK  A  B  C  D
0  Type1     1  1  1  1  1
1  Type2     2  2  2  2  2
2  Type3     3  3  3  3  3
3  Type4     4  4  4  4  4

Expected output

         A    C    B    D    A    C    B    D    A    C    B    D    A    C    B    D
WEEK     1    1    1    1    2    2    2    2    3    3    3    3    4    4    4    4
TYPE
Type1  1.0  1.0  1.0  1.0  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Type2  NaN  NaN  NaN  NaN  2.0  2.0  2.0  2.0  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Type3  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  3.0  3.0  3.0  3.0  NaN  NaN  NaN  NaN
Type4  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  4.0  4.0  4.0  4.0

My approach:

df1 = pd.DataFrame(df1)

colname = list(df1.head())
tuples = []

for i in colname:
    tuples.append((i,colname.index(i) 1))
    
index = pd.MultiIndex.from_tuples(tuples, names=["COLUMN", "ORDER"])   
df2 = pd.DataFrame(df1.values, columns=index)

df3 = pd.pivot_table(df1,index="TYPE",columns="WEEK", values=['A','B','C','D']).sort_index(level=1, axis=1)
#For df3 cannot attain the expected result because .sort_index(level=1, axis=1) will sort them out alphabetically to ['A','B','C','D']

.sort_index(level=1, axis=1) is required to swap the level of the pivot table.

Another dataframe df2 is generated in order to fix the order of columns as ['A','C','B','D'] to be used in the pivot table

COLUMN   TYPE WEEK  A  B  C  D
ORDER       1    2  3  4  5  6
0       Type1    1  1  1  1  1
1       Type2    2  2  2  2  2
2       Type3    3  3  3  3  3
3       Type4    4  4  4  4  4

CodePudding user response:

Create a CategoricalDtype before pivoting:

cat = pd.CategoricalDtype(['A', 'C', 'B', 'D'], ordered=True)

df3 = df.melt(['TYPE', 'WEEK'], var_name='COLUMN').astype({'COLUMN': cat}) \
        .pivot_table('value', 'TYPE', ['COLUMN', 'WEEK']).sort_index(level=1, axis=1)

Output

>>> df3
COLUMN    A    C    B    D    A    C    B    D    A    C    B    D    A    C    B    D
WEEK      1    1    1    1    2    2    2    2    3    3    3    3    4    4    4    4
TYPE                                                                                  
Type1   1.0  1.0  1.0  1.0  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Type2   NaN  NaN  NaN  NaN  2.0  2.0  2.0  2.0  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
Type3   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  3.0  3.0  3.0  3.0  NaN  NaN  NaN  NaN
Type4   NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  4.0  4.0  4.0  4.0
  •  Tags:  
  • Related