如何在 Streamlit 中将 Pandas DataFrame 下载到 CSV 文件

Posted

技术标签:

【中文标题】如何在 Streamlit 中将 Pandas DataFrame 下载到 CSV 文件【英文标题】:How do I download a Pandas DataFrame to a CSV File in Streamlit 【发布时间】:2021-12-10 19:22:31 【问题描述】:

我有一个大型 DataFrame,我想在 Excel 中探索并转移到其他应用程序。如何在我的 Streamlit 应用程序中将其下载为 CSV 文件?

【问题讨论】:

【参考方案1】:

From the docs,假设你有一个DataFrame my_large_df,你可以写一个函数:

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',
)

【讨论】:

【参考方案2】:
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',
)

【讨论】:

以上是关于如何在 Streamlit 中将 Pandas DataFrame 下载到 CSV 文件的主要内容,如果未能解决你的问题,请参考以下文章