【问题标题】:Why does second iteration always fail?为什么第二次迭代总是失败?
【发布时间】:2020-03-13 05:56:48
【问题描述】:

我正在尝试通过基于五个位置过滤数据框来创建 z_scores 的字典。

无论哪个位置在列表中,我总是将第一个键值对放入 dict,无论哪个位置是第二个,我总是得到这个错误:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2018.2.1\plugins\python\helpers\pydev\pydevd.py", line 1434, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2018.2.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 104, in <module>
    z_score = z_score(base, df['SalePrice'])
TypeError: 'numpy.float64' object is not callable

由于每个列表值在第一个时都有效,所以我不明白为什么每次后续迭代都会失败。

我的代码:

    def z_score(val, array, bessel=0):
        mean = array.mean()
        st_dev = std(array, ddof=bessel)
        distance = val - mean
        z = distance / st_dev

        return z


    neighborhoods = ['NAmes', 'CollgCr', 'OldTown', 'Edwards', 'Somerst']

    base = 200000
    z_scores = {}
    for neighborhood in neighborhoods:
        df = houses.loc[houses['Neighborhood'] == neighborhood]
        z_score = z_score(base, df['SalePrice'])
        z_scores[neighborhood] = z_score


    sorted_z_scores = sorted(z_scores.items(), key=lambda x: x[1], reverse=True)
    print(sorted_z_scores)

【问题讨论】:

  • 尝试使用不是'z_score, python is confusing your floating point z_score`的变量名和方法名z_score
  • 就是这样。非常感谢。
  • 听起来不错,我做了回答

标签: python-3.x pandas numpy


【解决方案1】:

在python中,解释器在本地范围内将变量名放在比方法名更高的优先级上,所以当你使用z_score作为变量名时,它会屏蔽对z_score方法名的访问,如果你改变z_score 变量的名称,您的代码应该运行。

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 2023-04-02
    • 1970-01-01
    • 2019-09-07
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多