pandas.DataFrame.drop()

DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

参数:

labels:要删除行、列的名字。

axis:默认为0,指删除行;axis=1指删除列。

index:直接指定要删除的行。

columns:直接指定要删除的列。

inplace:默认False,删除操作不改变原数据,而是返回一个执行删除操作后的新DataFrame;为True时,直接在原始数据上删除,删除后无法返回。

import pandas as pd
import numpy as np

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


# 删除列
print(df.drop('B', axis=1))
print(df.drop(['B', 'C'], axis=1))
   A   C   D
0  0   2   3
1  4   6   7
2  8  10  11
   A   D
0  0   3
1  4   7
2  8  11

# 删除行
print(df.drop(0))
print(df.drop([0, 1]))
   A  B   C   D
1  4  5   6   7
2  8  9  10  11
   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]])
print(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
print(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
print(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

来自:https://blog.csdn.net/songyunli1111/article/details/79306639

 
原文地址:https://www.cnblogs.com/keye/p/8977689.html