1
    brand         vehicleType
0   volkswagen      NaN
1   audi           coupe
2   jeep             suv
3   volkswagen     kleinwagen
4   skoda          kleinwagen
5   bmw             limousine
6   peugeot         cabrio
7   volkswagen      limousine
8   ford            bus
9   volkswagen     kleinwagen
10  mazda          limousine
11  volkswagen     kombi
12  volkswagen     kombi
13  volkswagen     kombi
14  nissan         suv

d=df.groupby(['brand','vehicleType']).vehicleType.count()

From the dataframe, I got the following table by performing the above operation

enter image description here

Now, how do I perform a descending sorting operation to the count column which is unnamed?

9
  • AttributeError: 'Series' object has no attribute 'columns', i think this error pops because d is not a dataframe?? Commented Jul 30, 2017 at 22:36
  • Yeah. If you could post your original data (as text), that would be great. Commented Jul 30, 2017 at 22:37
  • nope it doesn't come ,i just wanted the counted values to be sorted in descending, other than that rest all should be the same Commented Jul 30, 2017 at 22:54
  • I assume by "rest all should be the same" you mean you want to preserve the brand order. If that's the case, use d.sort_values(ascending=False).sort_index(level='brand', sort_remaining=False) Commented Jul 30, 2017 at 23:06
  • I got it.Thank you so much:) Commented Jul 30, 2017 at 23:07

1 Answer 1

2

You'll need to call Series.groupby(level=0). To sort each group, you can use a lambda with pd.Series.sort_values:

d.groupby(level=0).apply(lambda x: x.sort_values(ascending=False))

To get the largest item from each group, sorting is no longer necessary. use nlargest(1):

d.groupby(level=0, group_keys=False).apply(pd.Series.nlargest, n=1)
Sign up to request clarification or add additional context in comments.

2 Comments

What is group_keys? what does it do?
'group_keys=False' tell pandas that you don't want to add the group keys the the resulting dataframe (in this case it makes sense because your dataframe is already grouped with those keys)

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.