【问题标题】:How to correct UndefinedVariableError in python?如何纠正 python 中的 UndefinedVariableError?
【发布时间】:2023-01-08 18:31:25
【问题描述】:

当我为州名的一个特定值实现代码时(请参阅代码中的最后住所)

andhrapradesh.query('Duration_of_residence=="All durations of residence" & Last_residence_R_or_U=="Urban" & Last_residence=="Jammu & Kashmir"',inplace=True)
print(andhrapradesh['Total_migrants'].sum())

它给出了来自 pandas csv 的该状态所需的流出值总和。 但是,当我尝试计算所有可能的州名时,出现错误“UndefinedVariableError: name 'Jammu & Kashmir' is not defined”

states = ["Jammu & Kashmir","Punjab",'Himachal Pradesh']
for name in states:
    andhrapradesh.query(f'Duration_of_residence=="All durations of residence" & Last_residence_R_or_U=="Urban" & Last_residence=={name}',inplace=True)
    print(andhrapradesh['Total_migrants'].sum())

你能弄清楚为什么它显示错误吗?我该如何对列表状态中的所有值执行此操作。

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    您需要在 name 周围加上引号,就像您在手动代码中一样:

    df.query(f"... Last_residence == "{name}"")
    

    (也可以使用单引号...)

    但是,有更好的方法:您可以在变量前加上 @ 符号,这样您甚至不需要 f 字符串:

    df.query("... Last_residence == @name")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-29
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 2023-03-31
      • 2017-12-23
      相关资源
      最近更新 更多