Search code examples
pythonpandasdataframeslicemulti-index

Select 2 different set of columns from column multiindex dataframe


I have the following column multiindex dataframe.

enter image description here

I would like to select (or get a subset) of the dataframe with different columns of each level_0 index (i.e. x_mm and y_mm from virtual and z_mm rx_deg ry_deg rz_deg from actual). From what I have read I think I might be able to use pandas IndexSlice but not entire sure how to use it in this context.

So far my work around is to use pd.concat selecting the 2 sets of columns independently. I have the feeling that this can be done neatly with slicing.


Solution

  • You can programmatically generate the tuples to slice your MultiIndex:

    from itertools import product
    
    cols = ((('virtual',), ('x_mm', 'y_mm')),
            (('actual',),  ('z_mm', 'rx_deg', 'ry_deg', 'rz_deg'))
     )
    
    out = df[[t for x in cols for t in product(*x)]]