Issue with Clicking Specific Cells in a Streamlit Pivot Table to Display Filtered Data

We can select a cell in the dataframe but it does not return anything.

However, as of streamlit version 1.35.0, depending on what you try to achieve, we can now select a row, or column or both and it returns a meaningful info. This info can be further utilized to achieve our goal.

To activate selection, we will set the ‘on_select’ parameter to either ‘rerun’ or callable.

Example.

import streamlit as st
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]
}


df = pd.DataFrame(data)

event = st.dataframe(
    df,
    on_select='rerun',  # activate selection
)

selected_info = event['selection']
st.text(selected_info)

image

With the info returned, we can return the whole row data for that selected row or rows.

df = pd.DataFrame(data)

event = st.dataframe(
    df,
    on_select='rerun',  # activate selection
)

selected_info = event['selection']
st.text(selected_info)

st.markdown('**Selected dataframe**')
df_selected = df.loc[selected_info['rows']]
st.write(df_selected)

image

By default the users can select multiple rows. We can control that by the selection_mode parameter.

To limit the user to a single row selection, we will use the ‘single-row’ parameter value.

event = st.dataframe(
    df,
    on_select='rerun',  # activate selection
    selection_mode='single-row'
)

If you want the user to be limited to a single row and column.

event = st.dataframe(
    df,
    on_select='rerun',  # activate selection
    selection_mode=['single-row', 'single-column']
)

To get the cell value at the intersection.

df = pd.DataFrame(data)

event = st.dataframe(
    df,
    on_select='rerun',  # activate selection
    selection_mode=['single-row', 'single-column']
)

selected_info = event['selection']
st.text(selected_info)

st.markdown('**Selected dataframe**')
df_selected = df.loc[selected_info['rows']]
st.write(df_selected)

if len(selected_info['rows']) and len(selected_info['columns']):
    st.markdown('**Cell value at intersection**')
    cell_value = df.loc[selected_info['rows'][0], selected_info['columns'][0]]
    st.text(cell_value)
3 Likes