2

I'm successfully extracting and counting data from my dataframe but I'd like to sort on the resulting count values.

groupby snippet:

my_df.groupby('name').Id.nunique().head(5)

Results:

Name
nameA        4
nameB        1
nameC        1
nameD        6
nameE        2

But I'd like to order the results as follows;

Name
nameD        6
nameA        4
nameE        2
nameB        1
nameC        1

I'm assuming this should be straight forward and I'm hoping someone can point me in the right direction.

2

3 Answers 3

2

You don't even need the groupby. Just use value_counts().

>>> df.Name.value_counts()
nameD    6
nameA    4
nameE    2
nameC    1
nameB    1
Name: Name, dtype: int64
Sign up to request clarification or add additional context in comments.

2 Comments

This should be marked as the answer if there is guaranteed to be 1 unique id per name.
That's great! Thank you!
1

Try with:

my_df.groupby('name').Id.nunique().sort_values(ascending=False)

Comments

0

@ej_f - right on. Results for me were funny with nunique so I used count instead.

my_df.groupby('name').Id.count().sort_values(ascending=False)

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.