Search code examples
python-3.xpandasdataframegroup-byfillna

How to convert grouped index to regular index dataframe


I would like to convert a grouped index dataframe as the one down there:

              stock branches_code
products_code                     
1017626            5       Branch 23
                   1       Branch  7
                   1       Branch 44
                   1       Branch 43
                   1       Branch 46

To something like this:

              stock branches_code
products_code                     
1017626            5       Branch 23
1017626            1       Branch 7
1017626            1       Branch 44
1017626            1       Branch 43
1017626            1       Branch 46

In Pandas 1.4.x

Any Ideas would be greatly appreciated!

Update:

The script that created the grouped dataframe is this one:

sum_df = df.groupby(['products_code', 'branches_code']).agg({"stock": "sum"})

Solution

  • Use reset_index() for ungrouping your index and use set_index(column_name) for setting coulmn as index

    sum_df = df.groupby(['products_code', 'branches_code']).agg({"stock": "sum"})
    sum_df = sum_df.reset_index() # don't use drop=True
    

    Above line will give simple dataframe with a new index (numbered from 0 to n)