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

输入France作为地理参数时使用pandas query方法筛选数据出现ValueError报错求助

Fixing the ValueError in pandas query when filtering bank churn data by Geography

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:12:46