Home > Enterprise >  Color dataframe rows by condition in Pandas
Color dataframe rows by condition in Pandas

Time:02-23

I need to color rows in my DataFrame, according to the condition depending on some column. For example:

test = pd.DataFrame({"A": [1,2,3,4,5], "B":[5,3,2,1,4]})

def color(score):
    return f"background-color:"   (" #ffff00;" if score < 4 else "#ff0000") 

test.style.applymap(color, subset = ["A"])

But in this way I get color only at A column:

single column color

Also i can code like this:

def color1(score):
    return f"background-color: #ffff00;" 
def color2(score):
    return f"background-color: #ff0000;" 

temp = test.style.applymap(color1, subset = (test[test["A"]< 4].index, slice(None)))
temp.applymap(color2, subset = (test[test["A"] >= 4].index, slice(None)))

In this way color will be ok, but i struggle multiple calls of applymap functions. Is there any way to fulfill my goal without the multiple calls?

CodePudding user response:

In the first example, by the subset='A' you are telling to apply only to column A. If you remove that it will apply to the entire dataframe.

import pandas as pd
test = pd.DataFrame({"A": [1,2,3,4,5], "B":[5,3,2,1,4]})

def color(score):
    return f"background-color:"   (" #ffff00;" if score < 4 else "#ff0000") 

test.style.applymap(color)

ex1

If you want to apply different formatting in different columns you can easily design something handling one column at a time.

def color2(score):
    return f"background-color: #80FFff;" if score < 4 else None 
test.style.applymap(color, subset='A') \
          .applymap(color2, subset='B')

ex2

CodePudding user response:

If some complicated mask or set styles is possible create DataFrame of styles and pass to Styler.apply with axis=None:

def highlight(x):
    c1 = f"background-color: #ffff00;" 
    c2 = f"background-color: #ff0000;" 
    
    m = x["A"]< 4
    # DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    # set columns by condition
    df1.loc[m, :] = c1
    df1.loc[~m, :] = c2

    #for check DataFrame of styles
    print (df1)
    return df1


test.style.apply(highlight, axis=None)
  • Related