Pandas2.2 DataFrame
Reindexing selection label manipulation
方法 描述 DataFrame.add_prefix(prefix[, axis]) 用于在 DataFrame 的行标签或列标签前添加指定前缀的方法 DataFrame.add_suffix(suffix[, axis]) 用于在 DataFrame 的行标签或列标签后添加指定后缀的方法 DataFrame.align(other[, join, axis, level, …]) 用于对齐两个 DataFrame
或 Series
的方法 DataFrame.at_time(time[, asof, axis]) 用于筛选 特定时间点 的行的方法 DataFrame.between_time(start_time, end_time) 用于筛选 指定时间范围内的数据行 的方法 DataFrame.drop([labels, axis, index, …]) 用于从 DataFrame
中删除指定行或列的方法
pandas.DataFrame.drop()
pandas.DataFrame.drop()
是一个用于从 DataFrame
中删除指定行或列的方法。可以根据标签(label)删除整行或整列,常用于数据清洗和预处理。
📌 方法签名
DataFrame. drop( labels= None , * , axis= 0 , index= None , columns= None , level= None , inplace= False , errors= 'raise' )
🔧 参数说明:
参数 类型 说明 labels
单个标签或标签列表 要删除的行或列名(取决于 axis
) axis
{0/'index', 1/'columns'}
,默认为 0
指定删除的是行还是列 index
标签或标签列表 直接指定要删除的行索引(替代 labels
+ axis=0
) columns
标签或标签列表 直接指定要删除的列名(替代 labels
+ axis=1
) level
int 或 str,可选 多级索引时指定层级 inplace
bool
,默认 False
是否在原对象上修改 errors
{'ignore', 'raise'}
,默认 'raise'
如果标签不存在是否报错
✅ 返回值:
返回一个新的 DataFrame
,不修改原始数据(除非 inplace=True
)。
🧪 示例代码:
示例 1:删除列
import pandas as pd
df = pd. DataFrame( { 'A' : [ 1 , 2 , 3 ] , 'B' : [ 4 , 5 , 6 ] , 'C' : [ 7 , 8 , 9 ]
} )
df_drop_col = df. drop( columns= 'B' ) print ( "Original DataFrame:" )
print ( df)
print ( "\nAfter dropping column 'B':" )
print ( df_drop_col)
输出结果:
Original DataFrame:A B C
0 1 4 7
1 2 5 8
2 3 6 9After dropping column 'B':A C
0 1 7
1 2 8
2 3 9
示例 2:删除多列
df_drop_cols = df. drop( columns= [ 'A' , 'C' ] ) print ( "After dropping columns 'A' and 'C':" )
print ( df_drop_cols)
After dropping columns 'A' and 'C':B
0 4
1 5
2 6
示例 3:删除行(通过 labels + axis)
df_drop_rows = df. drop( [ 0 , 2 ] , axis= 0 ) print ( "After dropping rows 0 and 2:" )
print ( df_drop_rows)
After dropping rows 0 and 2:A B C
1 2 5 8
示例 4:使用 index
参数删除行
df_indexed = pd. DataFrame( { 'A' : [ 10 , 20 , 30 ] , 'B' : [ 40 , 50 , 60 ]
} , index= [ 'x' , 'y' , 'z' ] )
df_dropped_index = df_indexed. drop( index= 'x' ) print ( "After dropping index 'x':" )
print ( df_dropped_index)
After dropping index 'x':A B
y 20 50
z 30 60
示例 5:忽略不存在的标签
df_ignore = df. drop( columns= 'D' , errors= 'ignore' ) print ( "After trying to drop non-existent column 'D' with errors='ignore':" )
print ( df_ignore)
After trying to drop non-existent column 'D' with errors='ignore':A B C
0 1 4 7
1 2 5 8
2 3 6 9
🧠 应用场景:
数据清洗中删除无意义或冗余的列; 删除异常值所在的行; 预处理时移除缺失值较多的列; 构建特征集时剔除目标变量。
⚠️ 注意事项:
默认不会修改原始 DataFrame
,除非设置 inplace=True
; 若尝试删除不存在的标签,默认会抛出错误,可通过 errors='ignore'
忽略; 支持多级索引,可通过 level
参数指定层级。