1

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?

0

1 Answer 1

1

This is my current solution to this problem. Please comment and add your solutions.

Dropping works with pd.IndexSlice by running the slicer through the dataframe and extracting the index, then using that to drop the row:

df.drop(df.loc[ind,:].index)

                          amount
type   species    colour        
animal cat        black        1
plant  houseplant green       11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.