Home > OS >  Pandas Conditional formatting by comparing the column values of dataframe
Pandas Conditional formatting by comparing the column values of dataframe

Time:12-29

import io
import pandas as pd

csv_data = '''App_name,pre-prod,prod,stage
matching-image,nginx,nginx,nginx
mismatching-image,nginx,nginx,nginx:1.23.3-alpine'''

df = pd.read_csv(io.StringIO(csv_data), sep=",")
html_table = df.tohtml()

Is there a way to compare the values of columns in dataframe and use it in conditional formatting ? I want compare if the 'prod','pre-prod' and 'stage' values are mismatching, if yes then then its bg-color should be red. I have tired the following methods present in pandas but none of them works.

df.style.apply()

df.style.apply_index()

df.style.applymap()

Current Output:

enter image description here

Desired output:

enter image description here

CodePudding user response:

You can add style conditionally by applying style to a subset of your dataframe like:

import io
import pandas as pd

csv_data = '''App_name,pre-prod,prod,stage
matching-image,nginx,nginx,nginx
mismatching-image,nginx,nginx,nginx:1.23.3-alpine'''

def add_color(row):
    return ['background-color: red'] * len(row)

df = pd.read_csv(io.StringIO(csv_data), sep=",")
df.loc[(df["pre-prod"] == df["prod"]) & (df["prod"] == df["stage"])].style.apply(add_color, axis=1)

CodePudding user response:

import io
import pandas as pd

csv_data = '''
App_name,pre-prod,prod,stage
matching-image,nginx,nginx,nginx
matching-image,nginx,nginx,nginx
mismatching-image,nginx,nginx,nginx:1.23.3-alpine
mismatching-image,nginx,nginx,nginx:1.23.3-alpine
'''
df = pd.read_csv(io.StringIO(csv_data), sep=",")
def match_checker(row):
    if row['prod'] == row['pre-prod'] == row['stage']:
        return [''] * len(row)
    else:
        return ['background-color: red'] * len(row)
        
df = df.style.apply(match_checker, axis=1)

html_table = df.to_html()

with open('testpandas.html','w ') as html_file:
    html_file.write(html_table)
    html_file.close()

Updated @PeterSmith answer.

  • Related