Pandas:在 MultiIndex 数据帧中的每个索引之后添加一个空行

May*_*wal 10 python multi-index dataframe python-3.x pandas

考虑以下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
Run Code Online (Sandbox Code Playgroud)

如何在每个Name索引后添加一个空行?

预期输出:

              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
     
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 10

使用自定义函数在 中添加空行GroupBy.apply

def f(x):
    x.loc[('', ''), :] = ''
    return x
Run Code Online (Sandbox Code Playgroud)

或者:

def f(x):
    return x.append(pd.DataFrame('', columns=df.columns, index=[(x.name, '')]))
Run Code Online (Sandbox Code Playgroud)
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
                        
Run Code Online (Sandbox Code Playgroud)