简体   繁体   中英

How to sort the Values in Pandas Pivot table?

I have a pandas pivot_table and want to sort the 'Price'. How can I do that?

I tried to use sort_values but it returned ValueError.

df= pd.DataFrame({'ProductID':[78236,23658,12596,56302,48726,89235,86312,78541,10239,55563], 'Category':['Food','Food','Food','Food','Food','Food','Food','Food','Food','Food'], 'Price':[12,21,20,85,69,36,33,10,58,4]})
pivot = df.pivot_table(index=['ProductID'],columns=['Category'],values=['Price'],aggfunc='sum')
pivot.sort_values('Price', ascending=False)

I want to sort the 'Price' by descending order, but the error is: ValueError: The column label 'Price' is not unique. For a multi-index, the label must be a tuple with elements corresponding to each level.

Can anyone tell me how fix the code? Thanks a lot.

The expected output is: Output

This should fix it:

import pandas as pd

df = pd.DataFrame({'ProductID': [78236, 23658, 12596, 56302, 48726, 89235, 86312, 78541, 10239, 55563],
                   'Category': ['Food', 'Food', 'Food', 'Food', 'Food', 'Food', 'Food', 'Food', 'Food', 'Food'],
                   'Price': [12, 21, 20, 85, 69, 36, 33, 10, 58, 4]})
pivot = df.pivot_table(index=['ProductID'], columns=['Category'], values=['Price'], aggfunc='sum')
result = pivot.sort_values(('Price', 'Food'), ascending=False)
print(result)

Output

          Price
Category   Food
ProductID      
56302        85
48726        69
10239        58
89235        36
86312        33
23658        21
12596        20
78236        12
78541        10
55563         4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM