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

如何从Pandas DataFrame中移除包含指定列表元素的行?

解决Pandas移除指定人员行的问题

Got it, let's sort this out for you! The issue you're running into is that you're checking the index values against your name list, but what you actually need to target is the Names column itself. Here's how to fix it step by step:

1. First, avoid using list as a variable name

list is a built-in Python type, so using it as a variable will overwrite that core functionality. Let's rename your exclusion list to something like exclude_names instead:

import pandas as pd

df = pd.DataFrame({'Names': ['John', 'Edward', 'Sean'], 'Age': ['21', '44', '35']})
exclude_names = ['Edward', 'Martin', 'Paul']

2. Create a boolean mask for the rows to exclude

Instead of checking the index, use isin() directly on the Names column to flag rows you want to remove:

# This returns True for rows where Names is in the exclusion list
mask = df['Names'].isin(exclude_names)

For your data, this mask will be [False, True, False]—the True corresponds exactly to Edward's row.

3. Filter out the unwanted rows

Use the ~ operator to invert the mask (flip True to False and vice versa), then slice your DataFrame with this inverted mask:

filtered_df = df[~mask]

Alternative: Use df.query() for cleaner syntax

If you prefer a more readable one-liner, the query() method works great here too:

filtered_df = df.query("Names not in @exclude_names")

Why your original code didn't work

When you ran df.index.isin(list), you were checking if the DataFrame's default index values (0, 1, 2) are present in your name list. Since none of those numbers match the names you provided, you got a list of all False values—so no rows were filtered out.

Final Result

Either method will give you the desired DataFrame:

Names Age
0   John  21
2   Sean  35

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:44:02