Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to broadcast based on an index specification?

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)    

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading