changing value of every cell in dataframe to color the table

Viewed 205

Talking about console output only

I have a dataframe that looks something like this:

import pandas as pd

data = [{'a': 1.123, 'b': 'blabla', 'error': True}, {'a': 2.1342, 'b': 'bla', 'error': False}]
df = pd.DataFrame(data)

enter image description here

What I want to do is to color every cell, based on the value of the "error" cell in the relevant row. i.e. in this case, get this table:

For some reason ,this has bad indentation

I created this table by editing the data using colorama.

  • What I'm looking for is more like df.loc[df.error, <ALL_COLUMNS>] = colorama.Fore.RED + str(old_value) + colorama.Fore.RESET (and same for green)

How would I do that?


What I tried:

for col in df.columns:
   df[col] = df.apply(lambda x: Fore.RED + str(x[col]) + Fore.RESET if x[col] else Fore.GREEN + str(x[col]) + Fore.RESET, axis=1)

enter image description here

[X] indentation is bad, and going column by column which messes up the values


df.apply(lambda x: Fore.RED + str(x['error']) + Fore.RESET if x['error'] else Fore.GREEN + str(x['error']) + Fore.RESET, axis=1)

enter image description here

[X] looks better, but I miss all the values


df.apply(lambda x: Fore.RED + str(x) + Fore.RESET if x['error'] else Fore.GREEN + str(x) + Fore.RESET, axis=1)

enter image description here

[X] logically - works fine. Needs some tweaks

1 Answers

Try:

df = df.style.apply(lambda x: np.repeat('color: red' if x['error'] else '', x.shape[0]), axis=1)

When output to Excel it looks like...

enter image description here

Related