tomasbasham
tomasbasham

Reputation: 1734

Appending to Pandas multiindex

I have a Pandas Data Frame using a multi index that was created in the following way:

indices = [['one', 'two', 'three', 'four'], ['oob']]
index = pd.MultiIndex.from_product(indices, names=['first', 'second'])

results = pd.DataFrame(index=index, columns=['col1', 'col2', 'col3', 'col4', 'col5'])

... input values ...

                    col1    col2    col3    col4    col5
   first    second
     one    oob     0.87    0.56    0.46    0.50    0.48
     two    oob     0.87    0.57    0.23    0.33    0.26
   three    oob     0.76    0.25    0.36    0.30    0.33
    four    oob     0.73    0.23    0.38    0.29    0.33

What I would like to do is to add a further level (I believe that is the right term) into the Data Frame such that it will then look like this:

                    col1    col2    col3    col4    col5
   first    second
     one    oob     0.87    0.56    0.46    0.50    0.48
     one    meh     NaN     NaN     NaN     NaN     Nan
     two    oob     0.87    0.57    0.23    0.33    0.26
     two    meh     NaN     NaN     NaN     NaN     Nan
   three    oob     0.76    0.25    0.36    0.30    0.33
   three    meh     NaN     NaN     NaN     NaN     Nan
    four    oob     0.73    0.23    0.38    0.29    0.33
    four    meh     NaN     NaN     NaN     NaN     Nan

I have managed to achieve exactly this by recreating the index and then calling resutlts.reindex(index=index) but this seems a little long winded and requires I save the original indices in some variable. Is there a better way to do this.

For completeness I also tried using concat but I was really stabbing in the dark here.

Upvotes: 1

Views: 1508

Answers (1)

ALollz
ALollz

Reputation: 59549

.reindex can still work. There's no need to save the original indices, as you can get them from results directly.

import pandas as pd

newidx = [results.index.levels[0],
          results.index.levels[1].append(pd.Index(data=['meh']))]

results.reindex(pd.MultiIndex.from_product(newidx, names=results.index.names))

              col1  col2  col3  col4  col5
first second                              
one   oob      1.0   1.0   1.0   1.0   1.0
      meh      NaN   NaN   NaN   NaN   NaN
two   oob      1.0   1.0   1.0   1.0   1.0
      meh      NaN   NaN   NaN   NaN   NaN
three oob      1.0   1.0   1.0   1.0   1.0
      meh      NaN   NaN   NaN   NaN   NaN
four  oob      1.0   1.0   1.0   1.0   1.0
      meh      NaN   NaN   NaN   NaN   NaN

Upvotes: 2

Related Questions