'How to color text output from Pandas Dataframe in terminal (Linux)?

I want to be able to print data from data_dict with different colors based on the positive or negative value with Pandas DataFrame text in a linux terminal.

data_dict = {"Key1":[1,-2,3], "Key2":[1,2,-3]}

df = pd.DataFrame(data_dict)
print(df)

Is there a way to use colorama.Fore or something similar to somehow update the color of different cells as they are printed in the terminal?



Solution 1:[1]

Yes, there is a way, here is an example solution:

import pandas as pd
from termcolor import colored

data_dict = {"Key1":[1,-2,3], "Key2":[1,2,-3]}

df = colored(pd.DataFrame(data_dict), 'red')
print(df)

https://pypi.org/project/termcolor/

Edit:

also if you dont want to use imports

you can define a color and iterate the dic for the key values:

red = "\033[1;31m"
blue = "\033[1;34m"
data_dict = {"Key1":[1,-2,3], "Key2":[1,2,-3]}
for key in data_dict.keys () :
    print (red, key, blue, data_dict[key])

then you just put your condition on the key for the color

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1