Python – How to make all subindexes on multiindex have the same value

How to make all subindexes on multiindex have the same value… here is a solution to the problem.

How to make all subindexes on multiindex have the same value

I have a Dataframe with multiple indexes like this:

a 1
  2
  3
b 2
  3

So the values of the outer layer are a, b

, the inner layer of a is 1, 2, 3, and b is 2,3

I want to make sure that the index at the inner level is the same for all indexes at the outer level (in this case, a new row is created for b with the inner index being 1). For these new rows, the values on the columns will all be null.

Is there any easy way?

Solution

You can reindex using MultiIndex created from the original DataFrame index:

df.reindex(pd. MultiIndex.from_product(df.index.levels))

Example:

idx = pd. MultiIndex.from_arrays([['a','a','a','b','b'],[1,2,3,2,3]])

df = pd. DataFrame(np.random.random(5), index=idx)

>>> df
            0
a 1  0.354691
  2  0.322138
  3  0.195380
b 2  0.731177
  3  0.912628

>>> df.reindex(pd. MultiIndex.from_product(df.index.levels))
            0
a 1  0.354691
  2  0.322138
  3  0.195380
b 1       NaN
  2  0.731177
  3  0.912628

Related Problems and Solutions