1

Given the following pivot table:

import pandas as pd
import numpy as np
df = pd.DataFrame(
        {'YYYYMM':[201603,201503,201403,201303,201603,201503,201403,201303],
         'Count':[5,6,2,7,4,7,8,9],
         'Group':['A','A','A','A','B','B','B','B']})
df['YYYYMM']=df['YYYYMM'].astype(str).str[:-2].astype(np.int64)
t=df.pivot_table(df,index=['Group'],columns=['YYYYMM'],aggfunc=np.sum)
t
        Count
YYYYMM  2013    2014    2015    2016
Group               
A        7       2       6       5
B        9       8       7       4

I'd like to sort the rows (groups A and B) ascendingly by 2016 such that group B is above group A, while retaining the overall layout of the pivot table.

Thanks in advance!

1 Answer 1

3

Use sort_values

t.sort_values(('Count', 2016))

the tuple ('Count', 2016) is the name of the column you want to sort by.

looks like:

       Count               
YYYYMM  2013 2014 2015 2016
Group                      
B          9    8    7    4
A          7    2    6    5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.