First row in st.dataframe needs to be highlighted with a color

first row in st.dataframe needs to be highlighted with a color. Any suggestions please help.
Thanks
Sai

Here is an idea using pandas style.applymap. The trick to make the selection is in the tuple passed to the argument subset:

  • [0] refers to the first row
  • slice(None) refers to all the columns

image

import streamlit as st
import pandas as pd

df = pd.DataFrame({f"Column {i}": [*"abcdef"] for i in range(5)})

st.dataframe(
    df.style.applymap(
        lambda _: "background-color: CornflowerBlue;", subset=([0], slice(None))
    )
)
1 Like

Thank you very much Ed. Could you also suggest a quick example like this to highlight a particular cell based on any condition if possible please.
Thanks
Sai

You can tailor the conditionals in the callable passed to style.applymap.

For example, say we want to color the cells that have are vowel:
image

Or those cells that have a vowel and are in certain columns:
image

import streamlit as st
import pandas as pd

def color_vowel(value):
    return f"background-color: pink;" if value in [*"aeiou"] else None

df = pd.DataFrame({f"Column {i}": [*"abcdef"] for i in range(5)})

## Example 1
st.dataframe(df.style.applymap(color_vowel))

## Example 2
st.dataframe(df.style.applymap(color_vowel, subset=["Column 1", "Column 3"]))
2 Likes

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