Home > database >  python Dataframe: color cell of one column based on value
python Dataframe: color cell of one column based on value

Time:03-14

I have a DataFrame with different columns. On some column, I have a function that given a value returns a boolean: True if the value is valid, False if not. I want to display in red cells with invalid values.

Here is a simple example:

df = pd.DataFrame([
      { 'name': 'mercury', 'celsius_temperature': -120, 'age': 1.8 * 10**9 },
      { 'name': 'sun', 'celsius_temperature': 5666, 'age': 3*10**9 },
      { 'name': 'XRP-189', 'celsius_temperature': -1000000, 'age': 4*10**9 },
      { 'name': 'XZT-11', 'celsius_temperature': 10**19, 'age': 12 },
])

def is_temp_valid(temp):
      return (temp > -273.15) and (temp < 10**10)

def is_age_valid(age):
      return (age > 10**8) and (age < 13*10**9)

On this example I would like to display something like this: example colored dataframe

How to color cells in different columns based on different conditions on a DataFrame ?

I tried to use style with barckround_gradient: enter image description here

  • Related