Home > Mobile >  How to color text output from Pandas Dataframe in terminal (Linux)?
How to color text output from Pandas Dataframe in terminal (Linux)?

Time:02-24

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?

CodePudding user response:

you can use pandas built-in style , for example, to set background color :

def highlight_numbers(cell):
    if type(cell) != str and cell < 0 :
        return 'background: red; color:black'
    else:
        return 'background: black; color: white'

df.style.applymap(highlight_numbers)

for advanced styler, see Pandas doc

CodePudding user response:

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

  • Related