Vladislav
Vladislav

Reputation: 77

How to change index name in multiindex groupby object with condition?

I need to change 0 level index ('Product Group') of pandas groupby object, based on conditions (sum of related values in column 'Sales'). Since code is very long and some files are needed, I`ll copy output. the last string of code is:

tdk_regions = tdk[['Region', 'Sales', 'Product Group']].groupby(['Product Group', 'Region']).sum() 

###The output will be like this

Product Group                   Region  Sales
ALUMINUM & FILM CAPACITORS BG   America 7.425599e+07
                                China   2.249969e+08
                                Europe  2.404613e+08
                                India   6.034134e+07
                                Japan   7.667371e+06
... ... ...
TEMPERATURE&PRESSURE SENSORS BG Europe  1.308471e+08
                                India   3.077273e+06
                                Japan   2.851744e+07
                                Korea   1.309189e+06
                                OSEAN   1.258075e+07

Upvotes: 0

Views: 293

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195468

Try MultiIndex.rename:

df.index.rename("New Name", level=0, inplace=True)
print(df)

Prints:

                                             Sales
New Name                      Region              
ALUMINUM & FILM CAPACITORS BG America   74255990.0
                              China    224996900.0
                              Europe   240461300.0
                              India     60341340.0
                              Japan      7667371.0

Upvotes: 1

Related Questions