Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

truncating a pandas multindex at a given level

Say I have a pandas multi-index like so

                          var_0  var_1
    instances timepoints              
    0         1               1      4
              2               2      5
              3               3      6
              4               5      8
    1         1               1      4
              2               2     55
              3               3      6
              4               3      6
    2         1               1     42
              2               2      5
              3               3      6

How do I truncate it so for every instance I only have the first n timepoints? eg.2

                            var_0  var_1
    instances timepoints              
     0         1               1      4
               2               2      5
     1         1               1      4
               2               2      55
     2         1               1      42
               2               2      5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming multi-index df is df

df_new = df.groupby(level=0).head(2)
print(df_new)

#Haven’t tested…it should work..pls, Let me knwo if it deosn’t worked

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading