Home > other >  How to broadcast based on an index specification?
How to broadcast based on an index specification?

Time:08-18

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)    

CodePudding user response:

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
  • Related