0

I have a pandas data frame with a large MultiIndex. I'm selecting columns from this dataframe with various metadata that is in the index, like for example

current_row = df.xs(number, level='counter', drop_level=False, axis=1)

So far, so good. However, number comes from a list that might contain numbers that are not contained in the counter level in the index, so the above obviously fails with a KeyError.

So is there any way to test if my number exists, so that I can either continue with the number, or throw a custom error and continue with the next number?

isin sounds like it would be what I need, but I can't get it to work on my Multiindex.

JC_CL
  • 2,346
  • 6
  • 23
  • 36

1 Answers1

0

Tried a search with some different keywords again* and of course it's rather easily done with in:

if number in df.columns.get_level_values('counter'):
    #do stuff
else:
    #print my custom error

found for example here

*I hate it when that happens. You spend way too much time on something simple, finally give in and post a stupid question, and then you have a brainfart and solve it anyways and of course it was totally simple. Oh well…

JC_CL
  • 2,346
  • 6
  • 23
  • 36