NameError Handling

Hello.
I try to make an upload menu and make it into variable.
When the data have not been uploaded yet, the NameError occurs (there’s no problem when the data have been uploaded)

Error snippet:

NameError: name 'dataframe' is not defined
Traceback:

File "c:\Users\xx\Desktop\yy\zz\poc_v3\.venv\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 552, in _run_script
    exec(code, module.__dict__)
File "C:\Users\xx\Desktop\yy\zz\dinamic_ml\app.py", line 69, in <module>
    edited_dataframe = st.data_editor(dataframe)

I tried to handle it with try and except but doesn’t work.
Could you help me please?
Thank you.

Code snippet:

    # Setting the upload variabel
    uploaded_file = st.file_uploader("Choose a file to upload for training data",
                                     type="csv",
                                     help="The file will be used for training the Machine Learning")

    # Setting the upload options when there's file uploaded
    if uploaded_file is not None:
        try:
            # Can be used wherever a "file-like" object is accepted:
            dataframe = pd.read_csv(uploaded_file)
            st.write('Data Preview')
            st.write(dataframe)

            pr = dataframe.profile_report()
            st_profile_report(pr)

        except NameError:
            st.write("Please upload any data.")

Hi @little_death, and welcome to our forums!

The NameError you’re encountering is because you’re trying to access the dataframe variable in the line edited_dataframe = st.data_editor(dataframe) before the variable is defined. This happens when there’s no file uploaded, and the uploaded_file is not None condition is not met.

What about:

if uploaded_file is not None:
    dataframe = pd.read_csv(uploaded_file)
    st.write('Data Preview')
    st.write(dataframe)
    pr = dataframe.profile_report()
    st_profile_report(pr)
    
    # edit dataframe
    edited_dataframe = st.data_editor(dataframe)
else:
    st.write("Please upload any data.")
1 Like

Hello Sir @Charly_Wargnier,
Thanks for the warm regards.

The problem still occurs, since I use this scheme for loading and showing the same data in the three different tabs. Luckily, because of your reply I know how to do the work around.
Thank you!

1 Like

Glad this fixes it!

Happy Streamlitin’! :balloon:

Charly

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.