NameError :(“在赋值给封闭范围之前引用了自由变量'type'"; [英] NameError: ("free variable 'type' referenced before assignment in enclosing scope"

查看:918
本文介绍了NameError :(“在赋值给封闭范围之前引用了自由变量'type'";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码

dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) == list else x) for i in range(1, 7)}

将此列表的数据帧转换为数据帧的dict,如本

to convert a dataframe of lists to a dict of dataframes, as given in this thread. The line works when I use it in a console, but when I include it in my script I get this message:

NameError: ("free variable 'type' referenced before assignment in enclosing scope", 'occurred at index duration')

如果不发布我的整个脚本,您能否建议我应该寻找导致此错误的内容?脚本中没有使用type作为变量,在其他地方也没有将xi用作变量.

Without posting my whole script, can you suggest what I should be looking for that has generated this error? There is no use of type as a variable in the script, nor is x or i used elsewhere as a variable.

Traceback (most recent call last):
  File "C:/PYTHONprojects/DataDump/log_latest_from_api.py", line 138, in main
    dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) is list else x) for i in range(1, 7)}
  File "C:/PYTHONprojects/DataDump/log_latest_from_api.py", line 138, in <dictcomp>
    dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) is list else x) for i in range(1, 7)}
  File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4061, in apply
    return self._apply_standard(f, axis, reduce=reduce)
  File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4157, in _apply_standard
    results[i] = func(v)
  File "C:/PYTHONprojects/DataDump/log_latest_from_api.py", line 138, in <lambda>
    dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) is list else x) for i in range(1, 7)}
NameError: ("free variable 'type' referenced before assignment in enclosing scope", 'occurred at index duration'

推荐答案

以下是创建此类错误的最小方法:

Here is a minimal way to create such an error:

def foo():
    def bar():
        print(type)

    bar()
    type = 1

foo()

特别是type = 1存在的问题,但仅在尝试使用它的调用bar()之后.因此,尽管您说脚本中没有使用type作为变量",但我很难相信这一点.脚本中还对type进行了哪些提及?您是否给它分配了一个值,将其定义为函数或类的名称,或在任何地方导入了具有该名称的值?

In particular the problem the presence of type = 1, but only after the call to bar() which tries to use it. So while you say "There is no use of type as a variable in the script" I'm having trouble believing that. What other mentions of type in the script? Have you assigned it a value, defined it as the name of a function or class, or imported a value with that name anywhere?

这篇关于NameError :(“在赋值给封闭范围之前引用了自由变量'type'";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆