为什么我得到“赋值前引用的局部变量”?

2024-09-29 23:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过在列表中的每一项后面添加一个数字来从列表中创建新的列,但是出现了这个错误。你知道吗

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

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

Tags: columnsdataframedf列表indexlen错误range
1条回答
网友
1楼 · 发布于 2024-09-29 23:28:22

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)

相关问题 更多 >

    热门问题