I have a multi=indexed DataFrame, but I want to keep only two columns per level 1, for each of the level 0 variables (i.e. columns 'one' and 'two'). I can subset them separately, but I would like to do it together so I can keep the values side by side
Here is the DataFrame
index = pd.MultiIndex.from_tuples(list(zip(*[['bar1', 'foo1', 'bar1', 'foo2','bar3','foo3'], ['one','two','three','two','one','four']])))
df = pd.DataFrame(np.random.randn(2, 6), columns=index)
Here is the way to subset for one column in level 1
df.iloc[:, df.columns.get_level_values(1)== 'one']
# or
df.xs('one', level=1, axis=1)
# but adding two columns within either command will not work e.g.
df.xs(('one','two), level=1, axis=1)
This would be the expected output
bar1 foo1 foo2 bar3
one two two one
0 -0.508272 -0.195379 0.865563 2.002205
1 -0.771565 1.360479 1.900931 -1.589277