pandas
删除
看过来
《pandas 教程》 持续更新中,可作为 pandas 入门进阶课程、pandas 中文手册、用法大全,配有案例讲解和速查手册。提供建议、纠错、催更等加作者微信: gairuo123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。查看更新日志。作者开办 Python 数据分析训练营正在报名中,详情 Python 数据分析训练营。
![]() |
本教程作者所著新书《Python之光:Python编程入门与实战》(ISBN:9787111729891)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
![]() |
本教程作者所著新书《深入浅出Pandas:利用Python进行数据处理与分析》(ISBN:9787111685456)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
通过指定标签名称和相应的轴,或直接指定索引或列名称,删除行或列。 使用多索引时,可以通过指定级别来删除不同级别上的标签。
基本语法为:
# 语法
df.drop(labels=None, axis=0,
index=None, columns=None,
level=None, inplace=False,
errors='raise')
参数为:
原始数据:
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)
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
'''
删除行和列:
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
'''
这儿,可能有同学不理解 axis 为什么和 apply 中的逻辑不一致,其实是一致的,可以看看这个教程:axis 参数详解。