KeyError: df check code error before uploading data

Kindly need your support as i’m getting error after run code even i check if df is not None before run the code , but error dis appear after upload data

def loadData():
    data =pd.DataFrame()
    uploadFile= st.file_uploader("Choose output.csv file")
    if uploadFile is not None:
       df = pd.read_csv(uploadFile)
       data = df
    return data

df = loadData() 

if df is not None:
   def mergePop():
          #appended pop list
          #get US from df and get first 5 No to irritae
          #usList = df['UserName'].to_list()  
          for us in df['UserName'] :
              if us is not None:
                 if us[:2] == '02':
                 elif us[:2] == '03':
          popS= pd.Series(popList)      
          return popS
if df is not None:
   df['pop']=  pd.Series(mergePop())

KeyError: 'UserName'


File "c:\anaconda3\envs\elbouhy-env\lib\site-packages\streamlit\", line 332, in _run_script
    exec(code, module.__dict__)File "C:\Users\ramye\Desktop\", line 46, in <module>
    df['pop']=  pd.Series(mergePop())File "C:\Users\ramye\Desktop\", line 28, in mergePop
    for us in df['UserName'] :File "c:\anaconda3\envs\elbouhy-env\lib\site-packages\pandas\core\", line 3024, in __getitem__
    indexer = self.columns.get_loc(key)File "c:\anaconda3\envs\elbouhy-env\lib\site-packages\pandas\core\indexes\", line 3082, in get_loc
    raise KeyError(key) from err


Hi @ramyelbouhy, welcome to the Streamlit community!

Key Errors mean that the column you are trying to access doesn’t exist. The easiest way to debug this is to place a st.write(df.columns) in your code right before the for loop, to see what the values are actually named. Then you can either change the name of the column you are trying to reference, or possibly the column names aren’t coming through correctly on your pd.read_csv statement.


1 Like