Recently I wanted to use a pd.IndexSlice to drop some rows but realised they don't work together.
Here's an example:
data = [('animal', 'cat', 'black', 1),
('animal', 'mouse', 'grey', 5),
('plant', 'houseplant', 'green', 11)]
df = pd.DataFrame(data, columns=['type','species', 'colour', 'amount'])
df = df.set_index(['type','species','colour'])
idx = pd.IndexSlice
ind = idx[:,'mouse']
From this code we get a multi-indexed dataframe.
df
amount
type species colour
animal cat black 1
mouse grey 5
plant houseplant green 11
if you access that row index it will output:
df.loc[ind,:]
amount
type species colour
animal mouse grey 5
But if I want to use the same IndexSlice to drop some rows you will find out that it doesn't allow slicing:
df.drop(ind)
For this you'll get an error: TypeError: unhashable type: 'slice'
How can I use the IndexSlice to drop that row?