Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexible chaining in Python pandas

Setting

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.

My question

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.

Reproducible example

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
like image 868
KenHBS Avatar asked Mar 02 '23 02:03

KenHBS


1 Answers

Here is a way using style.apply and reversing the dict

mappings = [(mapping1, 'column_a'), (mapping2, 'column_b'), (mapping3, 'column_c')]

df.style.apply({v:k for k,v in mappings})

enter image description here

like image 66
anky Avatar answered Mar 15 '23 22:03

anky