Help styling arrows in dataframe

Hi @Daniel_Bishop :wave:

You can use a combination of applymap() and df.style.format() to add arrows and color cell values in one line.

  • df.style.format() formats the text displayed in value of cells.
  • .applymap() (elementwise): accepts a function that takes a single value and returns a string with the CSS attribute-value pair.

Note: I can only confirm this works for Streamlit versions 1.17.0 and the upcoming 1.18.0. Additionally, this solution colors the entire cell value, not just the arrows:

import numpy as np
import pandas as pd
import streamlit as st

def load_data():
    return pd.DataFrame(np.random.randint(-100, 100, size=(100, 2)), columns=list("ab"))

def _format_arrow(val):
    return f"{'↑' if val > 0 else '↓'} {abs(val):.0f}%" if val != 0 else f"{val:.0f}%"

def _color_arrow(val):
    return "color: green" if val > 0 else "color: red" if val < 0 else "color: black"

df = load_data()
st.dataframe(df)
styled_df = df.style.format(_format_arrow).applymap(_color_arrow, subset=["a", "b"])
st.dataframe(styled_df)

Hope this helps! :balloon:

3 Likes