Pythonista anonymous
Pythonista anonymous

Reputation: 8940

Pandas: pivot with rows and columns in a given order

I have a dataframe with hierarchical rows, which is the result of a transposed pivot. The second row index is a number and gets sorted in ascending order (which is what I want), but the first row index is a string and gets sorted alphabetically (which I don't want). Similarly, the column names are strings, and are sorted alphabetically, which I don't want.

How can I reorganise the dataframe so that rows and columns appear in the order I want? The only thing I though of is to rename them adding a number at the beginning, but it's messy and I'd rather avoid it, if possible.

A minimal example of what my data looks like is below.

import pandas as pd
import numpy as np

consdf=pd.DataFrame()

for mylocation in ['North','South']:
    for scenario in np.arange(1,4):
        df= pd.DataFrame()
        df['mylocation'] = [mylocation]
        df['scenario']= [scenario]
        df['this'] = np.random.randint(10,100)
        df['that'] = df['this']  * 2
        df['something else']  = df['this'] * 3
        consdf=pd.concat((consdf, df ), axis=0, ignore_index=True)

mypiv = consdf.pivot('mylocation','scenario').transpose()

Note on potential duplicates

I understand similar questions have been asked, but I couldn't apply any of those solutions to my multi-index.

Upvotes: 2

Views: 3032

Answers (1)

B. M.
B. M.

Reputation: 18628

The function reindex is for that, just adapt to manage columns :

In [1]: mypiv
Out[1]: 
mylocation               North  South
               scenario              
this           1            24     11
               2            19     53
               3            11     92
that           1            48     22
               2            38    106
               3            22    184
something else 1            72     33
               2            57    159
               3            33    276


In [2]: mypiv.reindex(['that', 'this', 'something else'], level=0) \
.T.reindex(['South','North']).T
Out[2]: 
mylocation               South  North
               scenario              
that           1            90     34
               2            50    104
               3           100    170
this           1            45     17
               2            25     52
               3            50     85
something else 1           135     51
               2            75    156
               3           150    255

Upvotes: 3

Related Questions