How to conditional format and convert a dataframe to an image using pandas?

Viewed 206

I want to conditional format a data frame and later convert it to an image.

Here is the base image and the specifications.

Raw Data

Specifications

  • Column key is unaffected
  • Column base has data bars
  • Rest all columns (c1 to c6) are conditional formatted together (conditional formatting together is important i.e the max value among all these columns will have the darkest colour and the minimum one will have the lightest colour), zeroes are removed and values are converted to %
  • Then this final dataframe should be converted to an image

Final Dataframe

1 Answers

Use pandas style function, see docs:

df.style.bar(subset="Base", color="#5fba7d").background_gradient(subset=["c1", "c2", "c3"])

I only used c2/3 in my example because you didn't provide the code to create this df and I had to write it myself... This gives you:

Styled image output


Update

df.style.bar(subset="Base", color="#5fba7d").background_gradient(subset=["c1", "c2", "c3"], axis=None)

With using axis=None the background is applied to the whole subset, instead of just one column at a time. See:

Updated output


Update using zeros as np.nan

df[df.loc[:, ["c1", "c2", "c3"]] == 0] = np.nan
df.style.bar(subset="Base", color="#5fba7d").background_gradient(subset=["c1", "c2", "c3"], axis=None)

Gives:

nan

Related