为什么我会得到“分配前已引用局部变量”?

时间:2019-05-10 12:22:04

标签: python pandas variables

我正在尝试通过在列表中的每个项目后面添加数字来从列表中创建新列,但出现此错误。

我试图将列表声明为“全局变量”,但是它不起作用。

colunasPes = ['numeroOrdem', 'nome']

df = pd.DataFrame(columns = colunasFam+colunasPes, index = range(len(lista)))

def criaColunas(i):#cria novas colunas no df para um novo membro
    for i in len(colunasPes):
        i = str(i)
        colunasNova[i] = colunasPes[i]+i
        colunasPes = colunasPes + colunasNova
    df = pd.DataFrame(columns = colunasFam+colunasPes, index = range(len(lista)))

criaColunas(1)

但是我得到了错误:

UnboundLocalError: local variable 'colunasPes' referenced before assignment

1 个答案:

答案 0 :(得分:2)

colunasPes = colunasPes + colunasNova在函数范围内引入了一个也称为colunasPes的新变量,因此您在赋值前要对其进行引用

您可以在函数中将其标记为global

def criaColunas(i):
    global colunasPes
    for i in len(colunasPes): #replace i? why pass it in?
        i = str(i)
        colunasNova[i] = colunasPes[i]+i
        colunasPes = colunasPes + colunasNova
    df = pd.DataFrame(columns = colunasFam+colunasPes, index = range(len(lista))) #this may not do what you want either

还是将其传递?

def criaColunas(i, colunasPes):
    # exactly as before

criaColunas(1, colunasPes)

顺便说一句-您传入i,然后在for循环中进行更改。那是故意的吗?

此外,您似乎正在尝试更改函数中不在范围内的另一个变量。

尝试返回数据框?

def criaColunas(i, colunasPes):
    global colunasPes
    for i in len(colunasPes): #replace i? why pass it in?
        i = str(i)
        colunasNova[i] = colunasPes[i]+i
        colunasPes = colunasPes + colunasNova
    return pd.DataFrame(columns = colunasFam+colunasPes, index = range(len(lista))) 

df =     criaColunas(1, colunasPes)