Search code examples
pythonpython-3.xpandasdataframemulti-index

Pandas: Add an empty row after every index in a MultiIndex dataframe


Consider below df:

              IA1  IA2  IA3
Name Subject               
Abc  DS        45   43   34
     DMS       43   23   45
     ADA       32   46   36
Bcd  BA        45   35   37
     EAD       23   45   12
     DS        23   35   43
Cdf  EAD       34   33   23
     ADA       12   34   25

How can I add an empty row after each Name index?

Expected output:

              IA1  IA2  IA3
Name Subject               
Abc  DS        45   43   34
     DMS       43   23   45
     ADA       32   46   36

Bcd  BA        45   35   37
     EAD       23   45   12
     DS        23   35   43

Cdf  EAD       34   33   23
     ADA       12   34   25
     

Solution

  • Use custom function for add empty rows in GroupBy.apply:

    def f(x):
        x.loc[('', ''), :] = ''
        return x
    

    Or:

    def f(x):
        return x.append(pd.DataFrame('', columns=df.columns, index=[(x.name, '')]))
    

    df = df.groupby(level=0, group_keys=False).apply(f)
    print (df)
                 IA1 IA2 IA3
    Name Subject            
    Abc  DS       45  43  34
         DMS      43  23  45
         ADA      32  46  36
                            
    Bcd  BA       45  35  37
         EAD      23  45  12
         DS       23  35  43
                            
    Cdf  EAD      34  33  23
         ADA      12  34  25