Created
November 28, 2024 05:51
-
-
Save skannan-maf/80b1df7f1263eca7841cd18ed21c5847 to your computer and use it in GitHub Desktop.
Streamlit select row of a Pandas dataframe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def st_select_rows_from_df(pdf, widget_base_key, exclusive=False, ignore_columns=[]): | |
| ''' | |
| This function displays each row with a selectable checkbox | |
| Users can select only one of them (or) any number of them depending on the argument "exclusive" | |
| Function returns a list of booleans indicating whether the corresponding row was selected or not | |
| ''' | |
| valid_cols = [col for col in pdf.columns if col not in ignore_columns] | |
| # Write header | |
| view_cols = st.columns(1+len(valid_cols)) | |
| with view_cols[0]: | |
| st.markdown('**Select**') | |
| for col_index in range(len(valid_cols)): | |
| with view_cols[col_index+1]: | |
| st.markdown('**{}**'.format(valid_cols[col_index])) | |
| # Currently selected keys | |
| state_key = widget_base_key+'/checked_state' | |
| # Useful function | |
| def r_key(r): | |
| return widget_base_key+'/checkbox/'+str(r) | |
| # Support for exclusive mode | |
| if exclusive and (state_key in st.session_state): | |
| newly_clicked = None | |
| for r_index in range(len(pdf)): | |
| if (st.session_state[r_key(r_index)]==True) and (r_index not in st.session_state[state_key]): | |
| newly_clicked = r_index | |
| break | |
| if newly_clicked is not None: | |
| for r_index in range(len(pdf)): | |
| if r_index != newly_clicked: | |
| st.session_state[r_key(r_index)] = False | |
| # Write down rows of the dataframe | |
| for r_index, r in pdf[valid_cols].iterrows(): | |
| view_cols = st.columns(1+len(r)) | |
| with view_cols[0]: | |
| checked = st.checkbox('Select', key=r_key(r_index)) | |
| for col_index in range(len(valid_cols)): | |
| with view_cols[col_index+1]: | |
| col_name = valid_cols[col_index] | |
| st.write('{}'.format(r[col_name])) | |
| if checked: | |
| if state_key not in st.session_state: | |
| st.session_state[state_key] = [r_index] | |
| else: | |
| if r_index not in st.session_state[state_key]: | |
| st.session_state[state_key] += [r_index] | |
| else: | |
| # If not checked, remove it from the session_state | |
| if state_key in st.session_state: | |
| st.session_state[state_key] = [x for x in st.session_state[state_key] if x != r_index] | |
| # Create output | |
| if state_key not in st.session_state: | |
| return [False]*len(pdf) | |
| return [True if r in st.session_state[state_key] else False for r in range(len(pdf))] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment