2017-06-20 78 views
0

對於繪圖,我基於條件(條件是熊貓數據框某些列中的某些值)定義顏色。現在我不確定,如果我在定義函數時犯了一個錯誤。 的功能如下:調用函數時出現「UnboundLocalError:引用前引用的本地變量」

def getColour(C, threshold): 
    neg = 0 - threshold 
    half = threshold/2 
    if C <= (neg - half): 
     clr = '#2b83ba' 
    if ((neg - half) < C <= neg): 
     clr = '#abdda4' 
    if ((threshold + half) > C >= threshold): 
     clr = '#fdae61' 
    if (C > (threshold + half)):  
     clr = '#d7191c' 
    return clr 

而且我這是怎麼實現它:我通過一個數據幀的行迭代,然後找到列滿足一個條件,使用指數從這些列從列表中獲取參數,應用另一個生成結果的函數(此函數起作用,當我爲繪圖設置固定顏色時腳本已經過測試並可正常工作),然後用不同的顏色繪製結果。

for index, row in Sparse.iterrows(): 
    lim = row[row.notnull()] 
    ci = [row.index.get_loc(x) for x in lim.index] 
    params = np.array(myList)[ci] 

    for i, w in enumerate(params): 
     w = w.tolist() 
     print w, w[2] 
     print ci[i] 
     colour = getColour(ci[i], threshold) 
     x, y = myFunction(w) 
     plt.plot(x,y, color=colour,linestyle='-',linewidth=1.5) 

但是,這將引發上線colour = getColour(ci[i], threshold)錯誤UnboundLocalError: local variable 'clr' referenced before assignment

我已閱讀處理此錯誤的其他帖子,但我看不到我的問題是什麼。

+0

我懷疑你的條件都不是獲取和'clr'從未分配,因此w ^如果你嘗試'返回clr',你會得到錯誤。 –

+2

你錯誤的最可能的原因是你的'if'語句沒有被測試'真',所以'clr'從未被定義過。這意味着你正在嘗試通過執行'return clr'來分配變量。一個簡單的解決方法是在'if'語句之前給'clr'一個默認值,比如'None'。 –

+0

我明白了,你是對的!我添加了初始版本並修改了值,但是現在我得到了'ValueError:一個Series的真值是不明確的。使用a.empty,a.bool(),a.item(),a.any()或a.all()。' – durbachit

回答

2

一般來說,鞏固您的病情邏輯是一個好主意。 你的clr會有所有這些價值嗎?沒有,所以你可以使用一些elif

def getColour(C, threshold): 
    neg = 0 - threshold 
    half = threshold/2 
    if C <= (neg - half): 
     clr = '#2b83ba' 
    elif ((neg - half) < C <= neg): 
     clr = '#abdda4' 
    elif ((threshold + half) > C >= threshold): 
     clr = '#fdae61' 
    elif (C > (threshold + half)):  
     clr = '#d7191c' 
    return clr 

然後做你的病情進行循環?你有沒有所有的情況下,如果?如果是,那麼在else中輸入錯誤是一個好主意。如果沒有,那麼這就是意味着你忘記了一個案例:

def getColour(C, threshold): 
    neg = 0 - threshold 
    half = threshold/2 
    if C <= (neg - half): 
     clr = '#2b83ba' 
    elif ((neg - half) < C <= neg): 
     clr = '#abdda4' 
    elif ((threshold + half) > C >= threshold): 
     clr = '#fdae61' 
    elif (C > (threshold + half)):  
     clr = '#d7191c' 
    else: 
     raise ValueError('Value expected for clr') 
    return clr 

編輯:爲了回答您的意見,我想你誤會我的意思。在Python中,如果出現意想不到的情況,最好拋出一個錯誤。 因此,要麼:

  • 你給一個默認的顏色值,如「白」,你用它正常
  • 將返回None,然後你的代碼的其餘部分應閱讀它之前檢查無 值(和那麼也許拋出錯誤)
  • 您可以直接拋出一個錯誤

PEP20: Errors should never pass silently.

+0

是的,這當然有用,謝謝!但是,現在我得到了'ValueError:一個Series的真值不明確。使用a.empty,a.bool(),a.item(),a.any()或a.all()。 – durbachit

+0

@durbachit我回答了您的評論 –

+0

啊,我明白了。不,你誤解了。我得到了'ValueError:一個Series的真值不明確。使用a.empty,a.bool(),a.item(),a.any()或a.all()。'AFTER我在if循環之前設置了一個默認顏色值並插入'raise ValueError('循環中clr')行的值。看起來它不能處理NaN。 – durbachit

相關問題