Reputation: 163
I have a pivot table which has incorrect column order and i need the columns to be in order as i wish
The below code is for pivot table:
data_frame1 = pd.pivot_table(data_frame, index=['PC', 'Geo', 'Comp'], values=['Bill', 'Bill2'], columns=['Month'], fill_value=0)
Code output
Bill1 Bill2
Month Jan Feb Jan Feb
PC Geo Comp
A Ind OP 1 1.28 1 1.28
B US OS 1 1.28 1 1.28
C Can OV 1 1.28 1 1.28
Expected output
Bill2 Bill1
Month Jan Feb Jan Feb
PC Geo Comp
A Ind OP 1 1.28 1 1.28
B US OS 1 1.28 1 1.28
C Can OV 1 1.28 1 1.28
Upvotes: 2
Views: 121
Reputation: 863541
Use DataFrame.reindex
by first level of MultiIndex
:
df = df.reindex(['Bill2','Bill1'], axis=1, level=0)
print (df)
Bill2 Bill1
Feb Jan Month Jan
A Ind 1 1.28 1 1.28
B US 1 1.28 1 1.28
C Can 1 1.28 1 1.28
Or if possible sorting in descending order:
df = df.sort_index(axis=1, level=0, ascending=False)
Upvotes: 2