如何在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:
- First verify that both target names are present in the
namecolumn. - 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 wherenameis 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
相关产品推荐
相关产品推荐

