从多索引Dataframe中删除特定行

mic*_*cha 7 python pandas

我有一个多索引数据框,如下所示:

 start      grad
 1995-96    1995-96 15  15  
            1996-97 6   6   
            2002-03 1   1   
            2007-08 1   1   
Run Code Online (Sandbox Code Playgroud)

我想降低第一级的特定值(级别= 0).在这种情况下,我想放弃第一个索引中1995-96的所有内容.

Pau*_*l H 12

pandas.DataFrame.drop 将level作为可选参数

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

从v0.18.1开始,它的docstring说:

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

    Parameters
    ----------
    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
"""
Run Code Online (Sandbox Code Playgroud)

  • 如果第一个索引没有被命名为 'start',你可以使用 `level=0` (2认同)