0

I have a data frame with two columns of an index like this.

             A                   B         
             one     two      three   four
ID
A       0.895717 -1.206412  1.431256 -1.170299
B       0.410835  0.132003 -0.076467  1.130127
C      -1.413681  1.024180  0.875906  0.974466

I want to filter it by first & second levels as mentioned below:

  1. I want to mention only the first level.

df[A]

             A                
             one     two    
ID
A       0.895717 -1.206412  
B       0.410835  0.132003 
C      -1.413681  1.024180
  1. I want to mention columns of second-level like this:

df[A[two],B[three,four]]

             A             B         
ID          two         three   four
A       -1.206412     1.431256 -1.170299
B       0.132003     -0.076467  1.130127
C       1.024180      0.875906  0.974466

Kindly help!

1 Answer 1

1

First selection:

df[['A']]
           A          
         one       two
ID                    
A   0.895717 -1.206412
B   0.410835  0.132003
C  -1.413681  1.024180

Second one:

df[[('A', 'one'), ('B', 'three'), ('B', 'four')]]

           A         B          
         one     three      four
ID                              
A   0.895717  1.431256 -1.170299
B   0.410835 -0.076467  1.130127
C  -1.413681  0.875906  0.974466

If really you have many combinations and want to compress the selector you could do something like:

l = [['A', 'one'], ['B', ['three', 'four']]]
idx = [(a,b) for A,B in l
       for a in (A if isinstance(A, list) else [A])
       for b in (B if isinstance(B, list) else [B])
       ]
df[idx]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. This representation looks great! l = [['A', 'one'], ['B', ['three', 'four']]] In this, if we mention it as l = [['A', []], ['B', ['three', 'four']]] no column from the A is printed. But, is there any way that I could print all the columns under A assuming that there are more than 100 features under A? Many Thanks!

Your Answer

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