pandas.io.formats.style.Styler.map — pandas 2.2.3 documentation (original) (raw)

Styler.map(func, subset=None, **kwargs)[source]#

Apply a CSS-styling function elementwise.

Updates the HTML representation with the result.

Parameters:

funcfunction

func should take a scalar and return a string.

subsetlabel, array-like, IndexSlice, optional

A valid 2d input to DataFrame.loc[], or, in the case of a 1d input or single key, to DataFrame.loc[:, ] where the columns are prioritised, to limit data to before applying the function.

**kwargsdict

Pass along to func.

Returns:

Styler

Notes

The elements of the output of func should be CSS styles as strings, in the format ‘attribute: value; attribute2: value2; …’ or, if nothing is to be applied to that element, an empty string or None.

Examples

def color_negative(v, color): ... return f"color: {color};" if v < 0 else None df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"]) df.style.map(color_negative, color='red')

Using subset to restrict application to a single column or multiple columns

df.style.map(color_negative, color='red', subset="A") ...
df.style.map(color_negative, color='red', subset=["A", "B"]) ...

Using a 2d input to subset to select rows in addition to columns

df.style.map(color_negative, color='red', ... subset=([0,1,2], slice(None)))
df.style.map(color_negative, color='red', subset=(slice(0,5,2), "A")) ...

See Table Visualization user guide for more details.