Reputation:
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
Upvotes: 1
Views: 15804
Reputation: 61910
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
Upvotes: 3