Hello, i have a locally run app where i used this technique to create a dtaframe with row selections. My question is if it is possible to make the dataframe work in a way that only one row is selectable, e.g. if one selected more then one row then the previous row would get unselected.
You can do this with the pandas style API, here’s a demo.
import streamlit as st
import pandas as pd
# Sample DataFrame
@st.cache_data
def load_data():
data = {
'A': range(10),
'B': range(10, 20),
'C': range(20, 30)
}
return pd.DataFrame(data)
df = load_data()
st.title('Highlight DataFrame Rows')
# Function to highlight odd/even rows
def highlight_odd_even(df, odd=True):
styles = []
for i in range(len(df)):
if (i % 2 == 0 and not odd) or (i % 2 == 1 and odd):
styles.append('background-color: yellow')
else:
styles.append('')
return ['background-color: yellow' if s else '' for s in styles]
highlight_odd = st.button('Highlight Odd Rows')
highlight_even = st.button('Highlight Even Rows')
if highlight_odd:
styled_df = df.style.apply(highlight_odd_even, odd=True)
st.dataframe(styled_df)
elif highlight_even:
styled_df = df.style.apply(highlight_odd_even, odd=False)
st.dataframe(styled_df)
else:
st.dataframe(df)