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

如何在Pandas DataFrame中查询同一列含指定双值的行?

Solution

Your current code fails because it uses & (logical AND) to check if a single name value contains both "Martin" and "Claire"—a condition no row can satisfy. To return both rows only if both names exist in the DataFrame, follow this approach:

Step-by-Step Fix:

  1. First verify that both target names are present in the name column.
  2. If both exist, filter the DataFrame to retrieve those rows; otherwise, return an empty DataFrame.

Working Code:

import pandas as pd

df = pd.read_csv('names.csv')
targets = {"Martin", "Claire"}

# Check if both names exist in the column
if targets.issubset(df['name']):
    # Keep only rows with the target names
    result = df[df['name'].isin(targets)]
else:
    # Return empty DataFrame matching original structure
    result = pd.DataFrame(columns=df.columns)

print(result)

Why This Works:

  • targets.issubset(df['name']) confirms every name in your target set is present in the DataFrame.
  • df[df['name'].isin(targets)] filters the DataFrame to retain only rows where name is in your target list.
  • If either name is missing, you get an empty DataFrame instead of partial results.

Alternative with query:

If you prefer using query, here's an equivalent version:

import pandas as pd

df = pd.read_csv('names.csv')
targets = ["Martin", "Claire"]

if all(name in df['name'].values for name in targets):
    result = df.query('name in @targets')
else:
    result = pd.DataFrame(columns=df.columns)

print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:55:24