micyukcha micyukcha - 11 months ago 138
Python Question

Drop specific rows from multiindex Dataframe

I have a multi-index dataframe that looks like this:

I'd like to drop by the specific values for the first level (level=0). In this case, I'd like to drop everything that has 1995-96 in the first index.

enter code here

start grad
1995-96 1995-96 15 15
1996-97 6 6
2002-03 1 1
2007-08 1 1

Answer Source

pandas.DataFrame.drop takes level as an optional argument

df.drop('1995-96', level='start')

As of v0.18.1, its docstring says:

Signature: df.drop(labels, axis=0, level=None, inplace=False, errors='raise') 
Docstring: Return new object with labels in requested axis removed.

    labels : single label or list-like
    axis : int or axis name
    level : int or level name, default None
        For MultiIndex
    inplace : bool, default False
        If True, do operation inplace and return None.
    errors : {'ignore', 'raise'}, default 'raise'
        If 'ignore', suppress error and existing labels are dropped.

    .. versionadded:: 0.16.1