Home > Software engineering >  How to save DataFrame as csv in streamlit?
How to save DataFrame as csv in streamlit?

Time:03-30

Hi I try to save my DataFrame as csv file in streamlit. My program return two Dataframes to streamlit as data. I want to make button that will allow to save this dataframes. I try this simple code:

if st.button("Pobierz plik"):
    data[0].to_csv('file.csv',index=False)

But nothing hapend when i clicked on the button. Any one have some idea?

CodePudding user response:

You need to use st.download_button

For streamlit > 1.0.0

Display a download button widget.

This is useful when you would like to provide a way for your users to download a file directly from your app.

Note that the data to be downloaded is stored in-memory while the user is connected, so it's a good idea to keep file sizes under a couple hundred megabytes to conserve memory.

A working example can be found here

In your case

@st.cache
 def convert_df(df):
     # IMPORTANT: Cache the conversion to prevent computation on every rerun
     return df.to_csv().encode('utf-8')

csv = convert_df(data[0])

st.download_button(
     label="Download data as CSV",
     data=csv,
     file_name='large_df.csv',
     mime='text/csv',
 )
  • Related