python - Pandas 合并在 Streamlit 中未按预期工作

标签 python pandas streamlit

摘要

在回调函数中使用 pandas merge 函数时,数据帧未正确更新。但是,pandas drop 函数按预期工作

请注意,虽然我已经打开了 st.cache。删除缓存功能时也会出现相同的行为。

重现步骤

代码片段:

import streamlit as st
import pandas as pd


@st.cache(allow_output_mutation=True)
def read_df():
    df = pd.DataFrame({
        'col1':[1,2],
        'col2':['A','B']
    })
    return df

df = read_df()

def do_something():
    global df
    df_new = pd.DataFrame({
        'col1':[1,2],
        'col3':["X","Y"]
    })
    df.drop(['col2'], axis = 1, inplace = True)
    df = df.merge(df_new, on="col1")

st.button("Do Something", on_click=do_something, args =())

download_csv = df.to_csv().encode('utf-8')
st.download_button('Download', data = download_csv, file_name = 'download_csv.csv', mime='text/csv')

重现行为的步骤

  • 点击“做某事”按钮
  • 点击“下载”按钮

预期行为:

我希望显示下载的 csv

   col1 col3
0     1    X
1     2    Y

实际行为:

但是,我得到以下输出

   col1 
0     1    
1     2   

调试信息

  • Streamlit 版本:1.16.0
  • Python版本:3.8.15
  • 使用 Conda:是
  • 操作系统版本:Windows 11
  • 浏览器版本:Edge v108.0.1462.54

最佳答案

我这样做的方法是从 session_state 存储和检索数据帧。多变的。这样您就知道您正在获取并使用最新的值。

  • st.session_state['df'] = df - 将“df” session 状态变量设置为当前 df
  • st.session_state['df'] = df1 - 将使用合并的 df 更新 session 状态变量

这是一个例子:

import streamlit as st
import pandas as pd

@st.experimental_memo
def read_df():
    df = pd.DataFrame({
        'col1':[1,2],
        'col2':['A','B']
    })
    st.session_state['df'] = df
    return df

df = read_df()

def do_something():
    df1 = st.session_state['df']
    df_new = pd.DataFrame({
        'col1':[1,2],
        'col3':["X","Y"]
    })
    df1.drop(['col2'], axis = 1, inplace = True)
    df1 = df1.merge(df_new, on="col1")
    st.session_state['df'] = df1

st.button("Do Something", on_click=do_something, args =())
df = st.session_state['df']
download_csv = df.to_csv().encode('utf-8')
st.download_button('Download', data = download_csv, file_name = 'download_csv.csv', mime='text/csv')

输出文件:

file_name = 'download_csv.csv'

   col1 col3
0     1    X
1     2    Y

注意:

@st.experimental_memo - 确保df加载一次

关于python - Pandas 合并在 Streamlit 中未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74973249/

相关文章:

Python 线程 'While' 不正常

Python SocketServer 监听多播

azure - 如何通过 Azure 容器应用程序部署 Streamlit 应用程序?

python - Streamlit 在 python 中更改按钮大小

python - 如何在 Streamlit 中使用plotly express 在 Y 轴上绘制多个值(相同单位)?

python - 一个处理程序可以同时处理 post 和 get Tornado 中的不同 URL

python - 如何根据pandas中另一列的频率值显示列值?

python - 将 cols 列表中的 NaN 值替换为其他 cols 列表的平均值

Python:使用不同大小的数据帧根据日期时间条件创建新列

python - 在 Python 中删除包含 "?"的行