pandas - Python: Sorting pivot table (multi index) -


i'm trying sort pivot table's values in descending order after putting 2 "row labels" (excel term) on pivot.

to create pivot, i'm using following function:

pt = pd.pivot_table(x, index = ['col1', 'col2'], values = 'col3', aggfunc = np.sum) 

i'm unable paste in table, in words, variable pt first sort col1, values of col2 within col1 col3 within of those. great, sort col3 (the values) while keeping groups broken out in col2 (this column can order , shuffled around).

the target output (col3 in descending order order in col2 group of col1):

                   col3     col1   col2                1     1.67              2     0.75              3     0.50       b       2     2.25              3     2.00               1     0.50       c       3     2.75              1     2.65              2     2.50  

i have tried code below, sorts entire pivot table values , loses grouping (i'm looking sorting within group).

    pt.sort_values(by = 'col3', ascending = false) 

for guidance, similar question asked (and answered) here, unable successful output provided output:

pandas: sort pivot table

the error answer "valueerror: keys need same shape"

any appreciated. thank you!

you need reset_index dataframe, sort_values col1 , col3 , last set_index multiindex:

df = df.reset_index()        .sort_values(['col1','col3'], ascending=[true, false])        .set_index(['col1','col2'])  print (df)            col3 col1 col2          1     1.67      2     0.75      3     0.50 b    2     2.25      3     2.00      1     0.50 c    3     2.75      1     2.65      2     2.50 

Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -