1

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: https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.background_gradient.html But I need to use it with my functions that returns booleans (the example i gave is simplified, some function are much more complex than just intervals). And also, the gradient is not exactly what I want (I just want a red color but this is a minor problem).

I also looked at https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html But I did not find an example with custom functions.

1 Answer 1

2

Possible solution is following:

import pandas as pd

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):
    if -273.15 < temp < 10**10:
        return 'background-color: red'


def is_age_valid(age):
    if 10**8 < age < 13*10**9:
        return 'background-color: red'


s = df.style.applymap(is_temp_valid, subset=['celsius_temperature'])
s = s.applymap(is_age_valid, subset=['age'])

s

Returns

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.