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

pandas MultiIndex: insert a row at top and keep first level of index hidden

In MultiIndex dataframe:

import pandas as pd
a = [['a', 'b', 2, 3], ['c', 'b', 5, 6], ['a','c', 8, 9]]
df = pd.DataFrame(a, columns=['I1', 'I2', 'v1', 'v2'])
df = df.groupby(['I1', 'I2']).first()

I want to insert a row ex at top and keep the first level of MultiIndex hidden. The expected result is

enter image description here

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

I tried concat:

data_ex = {'v1':[99], 'v2': [98]}
df_ex = pd.DataFrame(data_ex, index = [('ex','ex')])
pd.concat([df_ex, df])

However it become

enter image description here

I also tried first concat without index, then groupby multiply index. But pandas will automatically sort by MultiIndex. As a result, ex row cannot be set at top.

>Solution :

You need pass the correct index format

df_ex = pd.DataFrame(data_ex, index = pd.MultiIndex.from_tuples([('ex','ex')],names=["I1", "I2"]))

pd.concat([df_ex, df])
Out[783]: 
       v1  v2
I1 I2        
ex ex  99  98
a  b    2   3
   c    8   9
c  b    5   6
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