Saving a dataframe

Is there anyway to save a dataframe to my local pc? I’m trying to use:

if st.button(‘save dataframe’):
df.to_csv('mydf.csv)

But nothing happens when I click the button.

1 Like

Hi @Okita,

As far as I can tell you’re just missing the “writing to disk” part of the script that would accomplish what you want. I just tried this script and it worked – it wrote “df.csv” into the directory where streamlit was run when I pressed the button.

import streamlit as st
import pandas as pd

df = pd.DataFrame({'numbers': [1, 2, 3], 'colors': ['red', 'white', 'blue']})

st.write(df)
if st.button('save dataframe'):
    open('df.csv', 'w').write(df.to_csv())

This is assuming that you are simply trying to write the CSV to disk.

Does this accomplish what you need?

1 Like

Ohhh, ok! That’s it, thanks!

2 Likes

Oh great! Apologies for the long delay in response. We’re working on it!

1 Like

Hi!
I just start working with streamlit but I think it’s awesome… but… I can’t find any more advanced funtion in documentatnion :frowning:

And now I have a problem with save dataframe as file. I do everything like above:

if len(data_frame) == 0:
    st.write("Proszę załadować plik z osobnikami by uzyskać wynik i wygenerować raport.")
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('GENERUJ RAPORT DLA ZAKRESU'):
        open('table', 'w').write(table.to_csv())

but I got:

StreamlitAPIException : to_csv() is not a valid Streamlit command.

So it’s not working anymore in my example. How can I write that table as file?

Best regards! :slight_smile:

P.S.
Sorry for refreshing old thread but I think it’s a right place cos searching in internet solution, I got that link :slight_smile:

import streamlit as st
import pandas as pd
import io

# buffer to use for excel writer
buffer = io.BytesIO()

data = {
    "calories": [420, 380, 390],
    "duration": [50, 40, 45],
    "random1": [5, 12, 1],
    "random2": [230, 23, 1]
}
df = pd.DataFrame(data)

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

csv = convert_to_csv(df)

# display the dataframe on streamlit app
st.write(df)

# download button 1 to download dataframe as csv
download1 = st.download_button(
    label="Download data as CSV",
    data=csv,
    file_name='large_df.csv',
    mime='text/csv'
)

# download button 2 to download dataframe as xlsx
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
    # Write each dataframe to a different worksheet.
    df.to_excel(writer, sheet_name='Sheet1', index=False)

    download2 = st.download_button(
        label="Download data as Excel",
        data=buffer,
        file_name='large_df.xlsx',
        mime='application/vnd.ms-excel'
    )