【问题标题】:ValueError: expr must be a string to be evaluated, <class 'bool'> givenValueError: expr 必须是要评估的字符串,<class 'bool'> given
【发布时间】:2021-01-09 11:18:31
【问题描述】:

当我在下面的地理区域输入法国时,它给了我错误,有人可以帮忙吗?

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, &lt;class 'bool'&gt; given

【问题讨论】:

  • 不要使用query,而是使用churn_ds = pd.read_csv('...')['Geography'==geo]
  • 您好,您现在已经有了答案,您可以考虑accepting an answer 来奖励给您最有帮助的评论。

标签: python pandas string input


【解决方案1】:

方法DataFrame.query 需要一个string 作为参数,如果你想使用布尔语句,语法是不同的

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]

【讨论】:

  • df.query('Geography == @geo')
  • @SayanipDutta,您能否提供在这种情况下使用@ 的参考?
  • @navneethc 见here
  • 啊,谢谢。很高兴知道,但看起来它不适合经常使用。
【解决方案2】:

查询本身必须是一个字符串。您提供的是一个布尔表达式。

试试这个:

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

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

【讨论】:

    【解决方案3】:

    根据documentation,表达式必须是字符串。所以它必须用引号引起来。现在的问题是你如何引用现在是一个变量的“geo”。请参阅文档。

    参数

    expr:str
    
        The query string to evaluate.
    
        You can refer to variables in the environment by prefixing them with an ‘@’ character like @a + b.
    

    @sayandip-dutta 和 @azro 已经指出了这一点,您需要使用“@”符号,因为“geo”现在是一个变量。

    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)
    

    给出以下输出。

          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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-19
      • 2011-05-22
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      相关资源
      最近更新 更多