输入France作为地理参数时使用pandas query方法筛选数据出现ValueError报错求助
Hey there, let's break down and fix that ValueError you're hitting with your dataset code.
What's causing the error?
Your current line:
churn_ds = pd.read_csv('../input/predicting-churn-for-bank-customers/Churn_Modelling.csv', sep=",").query('Geography' == geo)
is actually evaluating the expression 'Geography' == geo first. Since 'Geography' is a literal string and geo is your input (like "France"), this comparison returns a boolean value (False in this case). The query() method expects a string-based expression to evaluate against the DataFrame's columns, not a boolean—hence the error expr must be a string to be evaluated, <class 'bool'> given.
Two straightforward fixes
1. Use an f-string with query()
Wrap your filter logic in a formatted string so query() receives the correct expression. We wrap {geo} in quotes because the Geography column contains string values:
geo = input("Select the country you´d like to analyze (France / Germany / Spain): ") churn_ds = pd.read_csv('../input/predicting-churn-for-bank-customers/Churn_Modelling.csv', sep=",").query(f'Geography == "{geo}"')
2. Use boolean indexing (often more intuitive)
Skip query() entirely and filter directly with a boolean mask—this avoids string formatting pitfalls:
geo = input("Select the country you´d like to analyze (France / Germany / Spain): ") df = pd.read_csv('../input/predicting-churn-for-bank-customers/Churn_Modelling.csv', sep=",") churn_ds = df[df['Geography'] == geo]
Bonus: Add input validation
To prevent unexpected errors from typos (like "france" instead of "France"), add a quick check for valid inputs:
allowed_countries = ['France', 'Germany', 'Spain'] geo = input("Select the country you´d like to analyze (France / Germany / Spain): ").strip() if geo not in allowed_countries: print(f"Oops, invalid input! Please choose one of: {', '.join(allowed_countries)}") else: df = pd.read_csv('../input/predicting-churn-for-bank-customers/Churn_Modelling.csv', sep=",") churn_ds = df[df['Geography'] == geo]
内容的提问来源于stack exchange,提问作者Mauricio Asperti

