pythonpandasdataframe

Conditionally color dataframe cells in python terminal


I have a dataframe.

import pandas as pd

data = {
    "Name": ['Alice','Bob', 'Sue','Joe','rose','cindy'],
    "Age": [11, 6, 3, 16, 21, 8],
    "Num": [2, 17, 12, 7, 22, 9],
    "Score": [3, 8, 13, 18, 3, 23],
    "Dep": [4, 19, 8, 11, 6, 20],
}

df = pd.DataFrame(data)

I want cells of column "Name" to be colored in python terminal which have "Age" greater than "Num"


Solution

  • You could use termcolor and a condition:

    # %pip install termcolor
    import termcolor
    
    out = (df.assign(Name=[termcolor.colored(n, 'red' if c else 'white')
                           for c, n in zip(df['Age'].gt(df['Num']), df['Name'])])
            # we also rename the column to ensure proper alignment
            .rename(columns={'Name': termcolor.colored('Name', 'white')})
          )
    
    print(out)
    

    Output:

    pandas termcolor conditional color