[Python] How to dynamically pick the columns to show in dataframe with streamlit

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to pick the columns to show dynamically in a streamlit dataframe.

    Below is the code

    #! /usr/bin/env python3
    import streamlit as st
    import pandas as pd

    st.set_page_config(layout="wide")

    # Create a sample dataframe with 3 columns Col1, Col2, Col3
    df = pd.DataFrame({
    'Col1': ['A', 'B', 'C'],
    'Col2': ['X', 'Y', 'Z'],
    'Col3': [1, 2, 3]
    })

    # Have a dropdown to select a column among Col1, Col2
    col = st.selectbox('Select a column', ['Col1', 'Col2'])

    # Show the dataframe with the selected column and column Col3
    st.dataframe(df, column_order=[col, 'Col3'], use_container_width=True)


    The issue is, irrespective of the selection, it always shows Col1 and Col3 always. As far as I can imagine, this might be because column_order is frozen when the dataframe is created the first time. But is this the intended behavior?

    The following code works dynamically to disable the dropdown based on checkbox, like its shown in examples.

    disable = st.checkbox('Disable the dropdown')
    sel = st.selectbox('Select a column', ['Col1', 'Col2'], key='sel', disabled=disable)


    Why is column_order different?

    I even tried using tuple to check if any python-mutable stuff is happening under the hood. But the behavior is same.

    st.dataframe(df, column_order=(col, 'Col3'), use_container_width=True)


    Am I missing something?

    Continue reading...

Compartilhe esta Página