2

I write a page in streamlit with button "Generate csv".

In code I have a pandas dataframe which is rendered in main page. I want to generate it to csv after click button.

I found on official forum answer how to do that, but It's not working in my example even if it's same.

[https://discuss.streamlit.io/t/saving-a-dataframe/677][1]

My code:

if len(data_frame) == 0:
    st.write("Please load file.")
else:
    min = st.number_input('Od:', 0, len(data_frame), 0)
    max = st.number_input('Do:', 0, len(data_frame), len(data_frame) )
    dataset = st.container()
    table = st.dataframe(data_frame.iloc[min:max])

    if st.button('Generate csv'):
        open('table', 'w').write(table.to_csv())

So as u can see the code is same as in example on forum. I also tried to create funtion in main script and call it from streamlit:

def generate_csv(df):
    
    df.to_csv('filename.csv')

And in both examples I got

StreamlitAPIException: to_csv() is not a valid Streamlit command

After click button, csv should be save on server.

Streamlit docs is poor and I can't found resolve for that example. Maybe someone had same problem and have solution?

1 Answer 1

1

From the docs, st.dataframe() is intended to display a dataframe as an interactive table.

You should not use that object (here called table) to call to_csv(), but instead use the original pd.DataFrame object (here called data_frame).

Update your code with the following:

if len(data_frame) == 0:
    st.write("Please load file.")
else:
    min = st.number_input('Od:', 0, len(data_frame), 0)
    max = st.number_input('Do:', 0, len(data_frame), len(data_frame) )
    dataset = st.container()
    table = st.dataframe(data_frame.iloc[min:max])

    if st.button('Generate csv'):
        generate_csv(data_frame.iloc[min:max])  # <-- see change
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.