ironv
ironv

Reputation: 1058

reorder columns at different levels in pandas pivot table

The dataframe shown below

df = pd.DataFrame(index=range(3), columns=['tr','ca','cy','value'])
df.loc[0] = [1,1,'x',20]
df.loc[1] = [1,0,'y',300]
df.loc[2] = [0,0,'x',300]
df['value'] = df['value'].astype(np.int)

which results in

  tr ca cy  value
0  1  1  x     20
1  1  0  y    300
2  0  0  x    300

can be pivoted as

pt = pd.pivot_table(df, values='value', index=['tr'], columns=['ca','cy'], fill_value=0)

which results in

ca    0        1
cy    x    y   x
tr
0   300    0   0
1     0  300  20

I need the order of 1/0 for tr and ca reversed. I realize I can do pt.loc[[1,0],] and that gets me tr in the right order. How do I do this for ca? The answer I am hoping for is

ca   1    0     
cy   x    x    y
tr
1   20    0  300
0    0  300    0

Upvotes: 0

Views: 603

Answers (1)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

You can use basic indexing provided by pandas like pt[[1,0]].loc[[1,0]] or if you want to deal with specific index in that multi index try reindexing i.e

pt.reindex(level='ca',columns=[1,0]).reindex(index=[1,0])

ca   1    0     
cy   x    x    y
tr              
1   20    0  300
0    0  300    0

Upvotes: 3

Related Questions