How to select single or multiple rows in st.dataframe and return the selected data?

I am using Streamlit for development and I noticed that st.dataframe does not have a built-in feature for selecting single or multiple rows. Later, I found that in st.data_editor, setting num_rows=dynamic allows for single or multiple row selection, but the selected data cannot be outputted.

Hello @Alex_Wang! :wave:

Welcome to our Streamlit community, itโ€™s great to have you with us! :hugs:

Hereโ€™s a super simple way to do it.

Export-1699343866327

And hereโ€™s the code for it:

import streamlit as st
import pandas as pd

df = pd.DataFrame({
    'Column A': [1, 2, 3, 4, 5],
    'Column B': ['A', 'B', 'C', 'D', 'E']
})

st.write('Dataframe:')
st.dataframe(df)

# Add a multiselect widget to select rows based on the index
selected_indices = st.multiselect('Select rows:', df.index)

# Subset the dataframe with the selected indices
selected_rows = df.loc[selected_indices]

# Display the selected data
st.write('Selected Rows:')
st.dataframe(selected_rows)

I hope this helps

Best,
Charly

Thank you very much. Your idea is very clever! However, it may be a bit cumbersome to operate if there are a lot of rows in st.dataframe. I hope to be able to achieve single or multiple selection by clicking on the rows in st.dataframe, with the selected rows changing color to indicate that they have been selected, and to save and retrieve the selected row data through st.session_state.

Hey @Alex_Wang,

Another way to do this would be using st.data_editor. Did you give a look at that page in our docs? Hereโ€™s a playground with the demo too:

CleanShot 2023-11-07 at 10.32.27

2 Likes

I would like to express my heartfelt gratitude for your invaluable assistance. As a beginner, your help has been incredibly important to me, and I truly appreciate it. Thanks to your guidance, my project can finally move forward. Your expertise and support have made a significant impact on my work, and I am deeply thankful for your kindness.

Once again, thank you for your time, patience, and willingness to help. I am truly grateful for the opportunity to learn from you, and I look forward to continuing to grow with your guidance.

Warm regards, Alex

2 Likes

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