St.dataframe selection: Unselect all programmatically?

I’m thrilled by the new row selection functionality of st.dataframe.

However, I’m struggling to find a way to un-select all the rows user has selected. Not even a hard st.rerun or a clear() on the cached dataframe seems to alter the selection. Is there a way to achieve this?

Context: I’m writing something like a very simple file manager for a RAG / LLM app, (ab)using st.dataframe as my file list. The dataframe is much faster than a very long list of selectboxes, and st.multiselect feels very weird for files. When the user has executed a function like moving or deleting files, I really want to reset the selection.

Hi @DCBB

Have you tried using session state for storing/modifying session state variables that can respond to user selection.

More info:

@dataprofessor, that’s what I would try usually, but I have not in this case, since, sadly, the documentation of st.dataframe states explicitly:

Selection states cannot be programmatically changed or set through Session State.

source

One way is to start from scratch by changing the key of the daframe.

import uuid

import streamlit as st
from streamlit import session_state as ss
import pandas as pd


data = {
    'Region': ['North', 'East', 'South', 'West', 'North', 'East'],
    'Product': ['CPU', 'Motherboard', 'HardDisk', 'GPU', 'CPU', 'GPU'],
    'Sales': [140, 120, 80, 600, 150, 620]
}


# Create an ss variable as key of dataframe.
if 'dfk' not in ss:
    ss.dfk = str(uuid.uuid4())


def execute_cb(sinfo):
    """Change the dataframe key.
    
    This is called when the button with execute label
    is clicked. The dataframe key is changed to unselect rows on it.
    """
    # print(sinfo)
    ss.dfk = str(uuid.uuid4())


def main():
    df = pd.DataFrame(data)

    event = st.dataframe(
        df,
        on_select='rerun',
        hide_index=True,
        key=ss.dfk
    )
    selected_info = event['selection']
    st.button('execute', on_click=execute_cb, args=(selected_info,))


if __name__ == '__main__':
    main()
2 Likes

@ferdy, oh sneaky! Thanks!

I still think it would be nice to able to do this without a hack, though.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.