I want to select multiple columns from a MultiIndex with multiple independent indexers. For example
df = pd.DataFrame(
np.zeros((2,4)),
columns=pd.MultiIndex.from_product([('a','b'),(1,2)])
)
from this DataFrame
a b
1 2 1 2
0 0 0 0 0
1 0 0 0 0
I want to select all columns under 'a'
plus ('b', 1)
, like df[[('a', 1), ('a', 2), ('b', 1)]]
, but I don't want to have to explicitly specify all levels of the columns below 'a'
.
What does not work:
df[['a', ('b', 1)]]
:KeyError: "[('b', 1)] not in index"
df.loc[:, ['a', ('b', 1)]]
:KeyError: "[('b', 1)] not in index"
df[[('a', slice(None)), ('b', 1)]]
:TypeError: unhashable type: 'slice'
df.loc[:, [pd.IndexSlice['a', :], ('b', 1)]]
:TypeError: unhashable type: 'slice'
Another similar thing I would like to be able to do is: ('a', 1)
plus pd.IndexSlice[:, 2]