Pandas .drop() 方法详解
.drop() 是 Python pandas 库中一个极其常用的函数,主要用于从 DataFrame 或 Series 中删除指定的行或列。
基本语法
df.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
核心参数说明
- labels: 要删除的行或列的标签(名称)。
- axis: 决定删除的方向。
axis=0或'index':删除行(默认值)。axis=1或'columns':删除列。
- index: 直接指定要删除的行索引(等同于
labels且axis=0)。 - columns: 直接指定要删除的列名(等同于
labels且axis=1)。 - inplace: 决定是否在原对象上修改。
False:返回一个删除后的新副本,原 DataFrame 不变(默认值)。True:直接修改原 DataFrame,不返回新对象。
- errors: 处理不存在的标签。
'raise':如果标签不存在,则抛出错误(默认值)。'ignore':如果标签不存在,则静默忽略。
常见使用场景与代码示例
假设我们有以下 DataFrame:
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris'],
'Score': [85, 90, 95]
}
df = pd.DataFrame(data, index=['row1', 'row2', 'row3'])
1 删除列 (Dropping Columns)
方法 A:使用 columns 参数(最直观)
# 删除单列 df_new = df.drop(columns=['Score']) # 删除多列 df_new = df.drop(columns=['Age', 'City'])
方法 B:使用 labels 和 axis=1
df_new = df.drop(['Score'], axis=1)
2 删除行 (Dropping Rows)
方法 A:使用 index 参数
# 删除单行 df_new = df.drop(index='row1') # 删除多行 df_new = df.drop(index=['row1', 'row3'])
方法 B:使用 labels 和 axis=0
df_new = df.drop(['row1'], axis=0)
3 原地修改 (Inplace Modification)
如果你不想创建新变量,而是想直接改变原数据,请使用 inplace=True。
df.drop(columns=['Score'], inplace=True) # df 已经失去了 'Score' 列,无需赋值给新变量
关键注意事项
- 返回值问题:初学者最容易犯的错误是调用
df.drop(...)后发现原数据没变,除非设置inplace=True,否则必须使用df = df.drop(...)来接收返回值。 - 索引匹配:删除行时,必须提供索引标签(Index Label),而不是行号(Integer Position),如果要根据行号删除,请先使用
df.index[n]获取标签,或使用df.iloc切片。 - 性能建议:在处理超大规模数据集时,频繁使用
inplace=True并不总是比赋值更快,建议根据具体内存情况选择。
快速总结表
| 目标 | 推荐写法 | 关键参数 |
|---|---|---|
| 删除列 | df.drop(columns=['列名']) |
axis=1 |
| 删除行 | df.drop(index=['索引名']) |
axis=0 |
| 永久删除 | df.drop(..., inplace=True) |
inplace=True |
| 防止报错 | df.drop(..., errors='ignore') |
errors='ignore' |
首发原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/490022.html



