简体   繁体   中英

How can I make a dataframe global? Getting error - UnboundLocalError: local variable referenced before assignment

I'm trying to take some data from a external process and continuously append it to a dataframe that I'll later upload into a DF but I'm getting this error:

UnboundLocalError: local variable 'financials_Balance_Sheet_yearlyDF' referenced before assignment

Here's what I'm doing:

global financials_Balance_Sheet_yearlyDF  
financials_Balance_Sheet_yearlyDF =  pd.DataFrame() 

def appendDFForTable(mainDF, DFtoAppend):
  
  mainDF = mainDF.append(DFtoAppend)
  return mainDF


def buildDFforUpload(tableName, DFtoAppend):
  if tableName == 'financials_Balance_Sheet_yearly': 
    financials_Balance_Sheet_yearlyDF =   appendDFForTable(financials_Balance_Sheet_yearlyDF, DFtoAppend) <<--this line is resulting in above error.

What am I doing wrong here? I thought that if I make the variable global or declare it outside of a function it would be accessible? My goal is to declare this variable and then expand it as I collect data from my process.

Update: As per Chris's comment - I am calling the function via buildDFforUpload('financials_Balance_Sheet_yearly', dfThatIWantToAppend)

when you want to use a global variable in python firt you have to create it like you do in line 2:

financials_Balance_Sheet_yearlyDF =  pd.DataFrame() 

then, in the function that use that variable you declare it as global:

def buildDFforUpload(tableName, DFtoAppend):
    global financials_Balance_Sheet_yearlyDF
    if tableName == 'financials_Balance_Sheet_yearly': 
        financials_Balance_Sheet_yearlyDF = appendDFForTable(financials_Balance_Sheet_yearlyDF, DFtoAppend) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM