How to style a Pandas dataframe cell by cell based on an auxiliary matrix?

Viewed 29

Suppose I have a simple dataframe of 2x2 size. In the color_matrix of the same size as the dataframe, it stores the color for each cell.

Question: How to style the dataframe given the color matrix? Also need to make sure the dataframe can be saved as an Excel file which has all the colorings.

d = {'col1': [1, 2], 'col2': [3, 4]}
color_matrix = [['Yellow', 'Red'],
                ['Green', 'Blue']]
df = pd.DataFrame(data=d)
df

When I read about the use examples of df.style.applymap, it conditions on individual value, but not seems using the index.

1 Answers

You can define an auxiliary function that takes the data frame, and returns a similarly-shaped data frame containing the CSS attribute strings. In this case, the function prepends the background-color: CSS attribute string:

def colors(df, color_matrix):
    # TODO: check sizes and resize color_matrix if necessary
    style_df = pd.DataFrame(color_matrix, index=df.index, columns=df.columns)
    return style_df.applymap(lambda elem: "background-color:" + elem.lower())

Then apply it with Styler.apply and axis=None (this is important):

df.style.apply(colors, axis=None, color_matrix=color_matrix)

Result:

Screenshot of styled dataframe

Related