You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于指定索引标签列表删除Pandas DataFrame中的行

根据索引标签列表删除DataFrame行的方法

要根据给定的索引标签列表name=[1, 5, 8, 10, 11, 20]删除DataFrame中的对应行,用pandas的drop()方法就能轻松实现,具体操作如下:

基础用法

假设你已经有一个DataFrame(比如名为df),直接调用drop()方法并传入索引列表即可:

# 生成删除后的新DataFrame,重新赋值给原变量
df = df.drop(name)

原地修改原DataFrame

如果不想重新赋值,直接修改原DataFrame,可以用inplace=True参数:

# 直接在原DataFrame上删除行,无需重新赋值
df.drop(name, inplace=True)

避免不存在索引的报错

如果列表里的某些索引标签在DataFrame中不存在,默认会抛出错误。添加errors='ignore'参数就能忽略这些不存在的索引:

# 仅删除存在的对应行,忽略不存在的索引
df = df.drop(name, errors='ignore')

完整示例代码

import pandas as pd

# 创建示例DataFrame(索引范围0-25)
df = pd.DataFrame({'数据列': range(26)}, index=range(26))
name = [1, 5, 8, 10, 11, 20]

# 执行删除操作
df = df.drop(name)
print(df)

内容的提问来源于stack exchange,提问作者Venkat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:02:06