I am applying two methods to a pandas Styler
object sequentially, like
df.style \
.applymap(mapping1, subset=["column_a"]) \
.applymap(mapping2, subset=["column_b"])
The mappings that I'm applying vary, though. For example, I may realise that I'd like to add a new mapping called mapping3
for column column_c
. For the sake for extensibility, I'd like to be able to quickly add a mapping and apply that too, without having to also add a line to the snippet above.
I want to flexibly provide mappings and apply them all to df
, where the input is a list of mappings (like mappings = [(mapping1, col1), (mapping2, col2), (mapping3, col3)]
and the output is a styled dataframe.
Even though this question uses the example of styled dataframes, I think this question is not limited to chaining styler objects per se. I think it would be relevant for all types of chaining methods in pandas.
import pandas as pd
df = pd.DataFrame({
"column_a": [-1, -2, 3, 4],
"column_b": ["good", "bad", "neutral", "amazing"],
"column_c": [0.1, 0.9, 0.5, 1]
})
def mapping1(val):
if val < 0:
color = "red"
elif val > 0:
color = "green"
else:
color = "black"
return "background-color: %s" % color
def mapping2(val):
if val == "amazing":
color = "purple"
else:
color = "black"
return "color: %s" % color
def mapping3(val):
if val < 0.8:
color = "orange"
if val >= 0.8:
color = "green"
return "color: %s" % color
styler = df.style \
.applymap(mapping1, subset=['column_a']) \
.applymap(mapping2, subset=["column_b"]) \
.applymap(mapping3, subset=["column_c"])
styler
We can execute applymap
inside a loop:
mappings = [
(mapping1, 'column_a'),
(mapping2, 'column_b'),
(mapping3, 'column_c')]
x = df.style
for m in mappings:
x = x.applymap(m[0], m[1])
x