How to broadcast based on an index specification?

Question:

I have the following input and use-case, note the index are arrays and when len is greater than one then means broadcast:

import pandas as pd 

df = pd.DataFrame([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]],
                  index=pd.Index([[1], [2, 3], [4]]),
                  columns=['a', 'b', 'c'])
print(df)

and would like to flatten the index in a way that broadcast the values as follows:

expected = pd.DataFrame([[1, 2, 3],
                         [4, 5, 6],
                         [4, 5, 6],
                         [7, 8, 9]],
                        index=[1, 2, 3, 4],
                        columns=['a', 'b', 'c'])
print(expected)    
Asked By: SkyWalker

||

Answers:

You can temporarily set the index as column, explode it and set it back as index:

df.reset_index().explode('index').set_index('index')

output:

       a  b  c
index         
1      1  2  3
2      4  5  6
3      4  5  6
4      7  8  9
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.