我正在使用此代码
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,如thread中所示。当我在控制台中使用它时,该行有效,但当我将其包含在我的脚本中时,我收到此消息:
NameError: ("free variable 'type' referenced before assignment in enclosing scope", 'occurred at index duration')
如果没有发布我的整个脚本,您能否建议我应该寻找产生此错误的内容?脚本中没有使用type
作为变量,x
或i
也不会在其他地方用作变量。
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'
答案 0 :(得分:0)
这是创建此类错误的最小方法:
def foo():
def bar():
print(type)
bar()
type = 1
foo()
特别是type = 1
存在的问题,但仅在调用尝试使用它的bar()
之后。因此,当你说“在脚本中没有使用type
作为变量时”我很难相信这一点。脚本中有哪些其他提及的type
?您是否为其分配了值,将其定义为函数或类的名称,或者在任何位置导入了具有该名称的值?