pandas.DataFrame.drop#

DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')[源代码]#

从行或列中删除指定的标签。

通过指定标签名称和相应的轴,或通过直接指定索引或列名称,删除行或列。使用多索引时,可以通过指定级别来删除不同级别上的标签。请参阅 user guide <advanced.shown_levels> 有关现在未使用的关卡的更多信息。

参数
labels单一标签或类似列表

要删除的索引或列标签。元组将被用作单个标签,而不被视为类似列表的标签。

axis{0或‘index’,1或‘Columns’},默认为0

是从索引(0或‘index’)还是从列(1或‘Columns’)中删除标签。

index单一标签或类似列表

指定轴的替代方法 (labels, axis=0 相当于 index=labels )。

columns单一标签或类似列表

指定轴的替代方法 (labels, axis=1 相当于 columns=labels )。

levelInt或Level名称,可选

对于多索引,表示将从中删除标签的级别。

inplace布尔值,默认为False

如果为False,则返回一个副本。否则,原地执行操作并返回None。

errors{‘忽略’,‘RAISE’},默认‘RAISE’

如果为‘Ignore’,则取消显示错误,并且只丢弃现有标签。

退货
DataFrame或无

不带删除的索引或列标签的DataFrame,如果 inplace=True

加薪
KeyError

如果在选定的轴中找不到任何标签。

参见

DataFrame.loc

基于标签位置的索引器,用于按标签选择。

DataFrame.dropna

在缺少(所有或任何)数据的情况下,返回带有给定轴上的标签的DataFrame。

DataFrame.drop_duplicates

返回删除了重复行的DataFrame,可以选择只考虑某些列。

Series.drop

删除了指定索引标签的返回系列。

示例

>>> df = pd.DataFrame(np.arange(12).reshape(3, 4),
...                   columns=['A', 'B', 'C', 'D'])
>>> df
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

删除列

>>> df.drop(['B', 'C'], axis=1)
   A   D
0  0   3
1  4   7
2  8  11
>>> df.drop(columns=['B', 'C'])
   A   D
0  0   3
1  4   7
2  8  11

按索引删除一行

>>> df.drop([0, 1])
   A  B   C   D
2  8  9  10  11

删除多索引数据帧的列和/或行

>>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
...                              ['speed', 'weight', 'length']],
...                      codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
...                             [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> df = pd.DataFrame(index=midx, columns=['big', 'small'],
...                   data=[[45, 30], [200, 100], [1.5, 1], [30, 20],
...                         [250, 150], [1.5, 0.8], [320, 250],
...                         [1, 0.8], [0.3, 0.2]])
>>> df
                big     small
lama    speed   45.0    30.0
        weight  200.0   100.0
        length  1.5     1.0
cow     speed   30.0    20.0
        weight  250.0   150.0
        length  1.5     0.8
falcon  speed   320.0   250.0
        weight  1.0     0.8
        length  0.3     0.2

从MultiIndex DataFrame中删除特定的索引组合,即删除该组合 'falcon''weight' ,它只删除相应的行。

>>> df.drop(index=('falcon', 'weight'))
                big     small
lama    speed   45.0    30.0
        weight  200.0   100.0
        length  1.5     1.0
cow     speed   30.0    20.0
        weight  250.0   150.0
        length  1.5     0.8
falcon  speed   320.0   250.0
        length  0.3     0.2
>>> df.drop(index='cow', columns='small')
                big
lama    speed   45.0
        weight  200.0
        length  1.5
falcon  speed   320.0
        weight  1.0
        length  0.3
>>> df.drop(index='length', level=1)
                big     small
lama    speed   45.0    30.0
        weight  200.0   100.0
cow     speed   30.0    20.0
        weight  250.0   150.0
falcon  speed   320.0   250.0
        weight  1.0     0.8