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:
Desired output:
3
Answers
Updated @PeterSmith answer.
You can add style conditionally by applying style to a subset of your dataframe like:
It’s also possible to style the entire DataFrame in one go by passing
axis=None
toapply
.We can identify rows which have differing values in the specified columns by comparing the first column (column 0) with the remaining columns (column 1-2) and identifying where there are unequal values using
ne
onaxis=0
.Then we can check across rows for
any
rows which have anyTrue
values (meaning there is something that’s not equal in the row).We can then simply apply the styles anywhere there’s a
True
value in the resulting Series.Altogether this could look something like:
Which produces the following:
Setup, version, and imports: