Amani Amani - 6 months ago 26
Python Question

Pandas, merging two rows with different index names

I have data frame,

df
, that looks like this:

Done Todo Total
Painting 55 54 109
Fitting 17 26 43
Plumbing 10 26 36
Electricity 7 29 36
Piping 29 5 34
Roofing 12 20 32


I need to merge indexes 'Plumbing' and 'Piping' so that I have a data frame that looks like this:

Done Todo Total
Painting 55 54 109
Fitting 17 26 43
Plumbing 39 46 68
Electricity 7 29 36
Piping 29 5 34


How can I achieve this is pandas?

I have tried the following

df.loc['Plumbing'] = df.loc['Plumbing'] + df.loc['Piping']


but this keeps the 'Piping' row in the data frame. Is there a way of doing it automatically so that the 'Piping row is automatically removed?
This and this questions did not provide what I need.

Answer

The easier is drop.

But you can replace values in index (first call to_series, because replace is not implemented in index) and then groupby by index with sum:

df.index = df.index.to_series().replace({'Piping':'Plumbing'}) 
print df
             Done  Todo  Total
Painting       55    54    109
Fitting        17    26     43
Plumbing       10    26     36
Electricity     7    29     36
Plumbing       29     5     34
Roofing        12    20     32

print df.groupby(df.index, sort=False).sum()
             Done  Todo  Total
Painting       55    54    109
Fitting        17    26     43
Plumbing       39    31     70
Electricity     7    29     36
Roofing        12    20     32
Comments