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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.