ValueError: expr must be a string to be evaluated, <class 'bool'> given

Viewed 4798

when I enter France for geo below it gives me the error, could someone please assist?

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('Geography' == geo)

#ValueError: expr must be a string to be evaluated, <class 'bool'> given

3 Answers

The method DataFrame.query expects a string as argument, if you want to use a boolean statement, the syntax is different

churn_ds = pd.read_csv('Churn_Modelling.csv', sep=",").query(f'Geography == "{geo}"')
churn_ds = pd.read_csv('Churn_Modelling.csv', sep=",").query(f'Geography == @geo') # takes geo variable

# Or

churn_ds = pd.read_csv('Churn_Modelling.csv', sep=",")
churn_ds = churn_ds[churn_ds['Geography'] == geo]

The query must itself be a string. What you have supplied is a Boolean expression.

Try this instead:

.query("Geography == {0}".format(geo)) (Python 3)

.query(f"Geography == {geo}") (Python >= 3.6)

As per the documentation, the expression has to be a string. So it must go in quotes. Now question is how do you refer to "geo" which is a variable now. See the documentation.

Parameters

expr:str

    The query string to evaluate.

    You can refer to variables in the environment by prefixing them with an ‘@’ character like @a + b.

This clarity has already been pointed out by @sayandip-dutta and @azro, you need to use '@' symbol since "geo" is a variable now.

import pandas as pd
geo = input("Select the country you´d like to analyze (France / Germany / Spain): ")

churn_ds = pd.read_csv('./Churn_Modelling.csv', sep=",").query(expr='Geography == @geo')
print(churn_ds)

Gives the following output.

      RowNumber  CustomerId  ... EstimatedSalary  Exited
1             2    15647311  ...       112542.58       0
4             5    15737888  ...        79084.10       0
5             6    15574012  ...       149756.71       1
11           12    15737173  ...        76390.01       0
14           15    15600882  ...        65951.65       0
...         ...         ...  ...             ...     ...
9966       9967    15590213  ...        20393.44       0
9980       9981    15719276  ...        99595.67       0
9987       9988    15588839  ...         1914.41       0
9989       9990    15605622  ...       179436.60       0
9992       9993    15657105  ...       195192.40       0

[2477 rows x 14 columns]
Related