對於繪圖,我基於條件(條件是熊貓數據框某些列中的某些值)定義顏色。現在我不確定,如果我在定義函數時犯了一個錯誤。 的功能如下:調用函數時出現「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
。
我已閱讀處理此錯誤的其他帖子,但我看不到我的問題是什麼。
我懷疑你的條件都不是獲取和'clr'從未分配,因此w ^如果你嘗試'返回clr',你會得到錯誤。 –
你錯誤的最可能的原因是你的'if'語句沒有被測試'真',所以'clr'從未被定義過。這意味着你正在嘗試通過執行'return clr'來分配變量。一個簡單的解決方法是在'if'語句之前給'clr'一個默認值,比如'None'。 –
我明白了,你是對的!我添加了初始版本並修改了值,但是現在我得到了'ValueError:一個Series的真值是不明確的。使用a.empty,a.bool(),a.item(),a.any()或a.all()。' – durbachit