How do I download a Pandas DataFrame to a CSV File in Streamlit

Viewed 1041

I have a large DataFrame that I'd like to explore in Excel and transfer to other applications. How do I download that as a CSV file in my Streamlit App?

2 Answers

From the docs, given you have a DataFrame my_large_df, you can write a function:

import streamlit as st

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


st.download_button(
  label="Download data as CSV",
  data=convert_df_to_csv(my_large_df),
  file_name='large_df.csv',
  mime='text/csv',
)
import streamlit as st

my_large_df = pd.read_csv('file.csv') #This is your 'my_large_df'

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

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