Marc Schwambach
Marc Schwambach

Reputation: 438

Repeat index of a DataFrame for each unique element in a MultiIndex

I am looking for a way in which I can repeat every element of a index for a given MultiIndex unique element.

So, assuming I am using the following code to create a empty data just with the index:

df_x1 = pd.DataFrame({'x1':np.linspace(1,4,4)}) 
df = pd.DataFrame(index = df_x1['x1'].values)

Now, I would like to create a multilevel indexing with the following data:

df_x2 = pd.DataFrame({'x2': np.linspace(0,2,3)})

Afterwards, I would like for each unique element of df_x2, set all the indexes in df_x1 as subindexes of df_2. So, finally, I would expect an empty dataframe with the results that resembles something like this:


0  1
   2
   3
   4
1  1
   2
   3
   4
2  1
   2
   3
   4

Upvotes: 2

Views: 1149

Answers (1)

jezrael
jezrael

Reputation: 863166

I think you need MultiIndex.from_product for MultiIndex of all combinations:

mux = pd.MultiIndex.from_product([df_x2['x2'], df.index])
print (mux)
MultiIndex([(0.0, 1.0),
            (0.0, 2.0),
            (0.0, 3.0),
            (0.0, 4.0),
            (1.0, 1.0),
            (1.0, 2.0),
            (1.0, 3.0),
            (1.0, 4.0),
            (2.0, 1.0),
            (2.0, 2.0),
            (2.0, 3.0),
            (2.0, 4.0)],
           )

And then pass to DataFrame constructor:

df2 = pd.DataFrame(index=mux)

Or if data in df are not empty and is necessary repeat rows add DataFrame.reindex:

df2 = df.reindex(mux, level=1)
print (df2)
Empty DataFrame
Columns: []
Index: [(0.0, 1.0), (0.0, 2.0), (0.0, 3.0), (0.0, 4.0), (1.0, 1.0), 
        (1.0, 2.0), (1.0, 3.0), (1.0, 4.0), (2.0, 1.0), (2.0, 2.0), 
        (2.0, 3.0), (2.0, 4.0)]

print (df2.index)
MultiIndex([(0.0, 1.0),
            (0.0, 2.0),
            (0.0, 3.0),
            (0.0, 4.0),
            (1.0, 1.0),
            (1.0, 2.0),
            (1.0, 3.0),
            (1.0, 4.0),
            (2.0, 1.0),
            (2.0, 2.0),
            (2.0, 3.0),
            (2.0, 4.0)],
           )

Upvotes: 2

Related Questions