0

I would like to know how to pass from a multiindex dataframe like this:

A            B
col1   col2  col1   col2
1       2      12     21
3       1       2      0

To two separated dfs. df_A:

  col1   col2    
   1       2      
   3       1

df_B:

   col1   col2
    12     21
     2      0

Thank you for the help

TCosm
  • 29
  • 4

1 Answers1

1

I think here is better use DataFrame.xs for selecting by first level:

print (df.xs('A', axis=1, level=0))
   col1  col2
0     1     2
1     3     1

What need is not recommended, but possible create DataFrames by groups:

for i, g in df.groupby(level=0, axis=1):
    globals()['df_' + str(i)] =  g.droplevel(level=0, axis=1)

print (df_A)
   col1  col2
0     1     2
1     3     1

Better is create dictionary of DataFrames:

d = {i:g.droplevel(level=0, axis=1)for i, g in df.groupby(level=0, axis=1)}
print (d['A'])
   col1  col2
0     1     2
1     3     1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252