2

A similar question to Slice Pandas dataframe by index values that are (not) in a list, in the particular case of multi index slicers.

Sample data copied from help(df.loc):

import pandas
tuples = [
   ('cobra', 'mark i'), ('cobra', 'mark ii'),
   ('sidewinder', 'mark i'), ('sidewinder', 'mark ii'),
   ('viper', 'mark ii'), ('viper', 'mark iii')
]
index = pandas.MultiIndex.from_tuples(tuples)
values = [[12, 2], [0, 4], [10, 20],
        [1, 4], [7, 1], [16, 36]]
df = pandas.DataFrame(values, columns=['max_speed', 'shield'], index=index)

Multi index slicing can be used to select all rows that contain "mark i" as their second index:

idx = pandas.IndexSlice
df.loc[idx[:, "mark i"],:]

I would like to inverse the selection. The result should contain all rows that do not contain "mark i" as their second index.

Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110

1 Answers1

3

An easy method would be to use isin:

df.loc[~df.index.isin(["mark ii"], level=1)]

                     max_speed  shield
cobra      mark i           12       2
sidewinder mark i           10      20
viper      mark iii         16      36

pandas index.isin allows checks on a particular level, in this case, we are interested in the second level (level = 1)

sammywemmy
  • 27,093
  • 4
  • 17
  • 31