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 add multiindex columns to existing df, preserving original index

I start with:

df
   0  1  2  3  4
0  5  0  0  2  6
1  9  6  5  8  6
2  8  9  4  2  1
3  2  5  8  9  6
4  8  8  8  0  8

and want to end up with:

df
         0  1  2  3  4
A  B  C
1  2  0  5  0  0  2  6
      1  9  6  5  8  6
      2  8  9  4  2  1
      3  2  5  8  9  6
      4  8  8  8  0  8

where A and B are known after df creation, and C is the original
index of the df.

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

MWE:

import pandas as pd
import numpy as np


df = pd.DataFrame(np.random.randint(10, size=(5, 5)))
df_a = 1
df_b = 2

breakpoint()

What I have in mind, but gives unhashable type error:

df.reindex([df_a, df_b, df.index])

>Solution :

Tru with pd.MultiIndex.from_product

df.index = pd.MultiIndex.from_product([[1],[2],df.index],names = ['A','B','C'])
df
Out[682]: 
       0  1  2  3  4
A B C               
1 2 0  7  0  1  9  9
    1  0  4  7  3  2
    2  7  2  0  0  4
    3  5  5  6  8  4
    4  1  4  9  8  1
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