How can I reset the index in a .groupby output?

Hi all,

I have the following dataframe. I want to group the name and brand columns by their respective unique values.

I wrote the following python code to group them:

high_products = products.reset_index().groupby(['name', 'brand'])[['name', 'brand', 'count_name']]

and printed the output with the following code:

high_products.head().sort_values(by='count_name', ascending=False)


As you can see from the image above, it appears that it is grouping them also based on the index. In the end, I just want to get the unique name and brand values and their respective count names.

How can I do this with .groupby?

Thank you.

1 Like


The only thing I see here is that you did not use an aggregate function after grouping.

Here I used sum


import pandas as pd
data_dict = [
            {'name': 'Ariel', 'Brand': 'P&G', 'Count': 10},
            {'name': 'Ariel', 'Brand': 'P&G', 'Count': 15},
            {'name': 'Gillete', 'Brand': 'P&G', 'Count': 4},
            {'name': 'Gillete', 'Brand': 'P&G', 'Count': 11},
            {'name': 'Gillete', 'Brand': 'P&G', 'Count': 9},
            {'name': 'Pamper', 'Brand': 'P&G', 'Count': 100},
            {'name': 'Pamper', 'Brand': 'P&G', 'Count': 23},
            {'name': 'Pamper', 'Brand': 'P&G', 'Count': 150},
            {'name': 'Imperial Leather', 'Brand': 'PZ', 'Count': 30},
            {'name': 'Joy Soap', 'Brand': 'PZ', 'Count': 100},
            {'name': 'Imperial Leather', 'Brand': 'PZ', 'Count': 30},
            {'name': 'Joy Soap', 'Brand': 'PZ', 'Count': 100}
pd.DataFrame(data_dict).groupby(['name', 'Brand']).sum().sort_values(by='Count')



Thank you. This solved my problem.

1 Like