2017-05-04 44 views
0

「自由變量‘類型’在封閉的範圍分配前引用了」我使用這個代碼NameError:(

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

以列表的數據幀,轉換成dataframes的字典在本thread給出的線工程時,我在一個控制檯使用它,但是當我有它在我的腳本中,我得到這個消息:

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

沒有張貼我的整個腳本,你可以建議產生了什麼我應該尋找的是這個錯誤?沒有使用type作爲腳本中的變量,xi也不在其他地方用作變量。

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

在您的控制檯中,在您的'dof = ...'之前,執行print(pd .__ version__),並在log_latest_from_api.py腳本中包含print(pd .__ version__)。什麼是輸出? – Allen

+0

有沒有可能你不小心重新分配了類型?你可以通過使用Series.dtype來代替type()來測試x中對象的類型。 – Stael

+0

@Allen都顯示版本'0.18.1' – doctorer

回答

0

下面是創建這樣的錯誤最小方式:

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

    bar() 
    type = 1 

foo() 

特別問題的type = 1存在,但只有調用bar()它試圖使用它之後。所以,當你說「在腳本中沒有使用type作爲變量」,我很難相信這一點。腳本中還有什麼其他的提及type?你給它賦了一個值,將它定義爲一個函數或類的名字,或者在任何地方用這個名字導入一個值?

+0

我找到了。我的異常處理有這樣一行:'type,value,tb = sys.exc_info()' - 我認爲這是導致錯誤的原因。謝謝 – doctorer