df 状态
df.drop(self, labels=None, axis=0|1, index=None, columns=None, level=None, inplace=False|True, errors='raise| ignore')
labels : 列名称 或者 行|列索引号
labels, axis=0 等价于 index=labels ;
labels, axis=1 等价于 columns=labels
inplace=False|True : 是否替代原来的df, 默认False(不替代)
errors='raise| ignore' : 是否忽略错误, 默认raise(报错), ignore为跳过错误继续运行
level 用于多重index,第几层
index 状态
Index.drop(self,labels,errors='raise')
Examples
Drop columns 删除列
df.drop(['B', 'C'], axis=1) 等价于 df.drop(columns=['B', 'C'])
A D
0 0 3
1 4 7
2 8 11
Dropa row by index 删除行 (双闭区间)
df.drop([0, 1])
A B C D
2 8 9 10 11
删除行&列
df.drop(columns=['B', 'C'],index = [0:2])
Dropcolumns and/or rows of MultiIndex DataFrame 从多层索引删除行|列
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
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