2

The objective is to highlight a cell if it contain * or **.

I have the impression this can be achieved as below

import numpy as np
import pandas as pd

df = pd.DataFrame ( {'Data': ['foo', '*', 'bar'],
                     'myda': ['**', '*', 'wer']} )


def highlight_ (s, props=''):
    return np.where ( s.str.contains ( "*" ), props, '' )


df.apply ( highlight_, props='background-color:yellow', axis=1 )

However, the compiler return an re.error.

re.error: nothing to repeat at position 0

May I know how to properly implement this?

2
  • 1
    s.str.contains ("\*"). You have to escape the asterisk. Commented Sep 4, 2021 at 8:03
  • 1
    also i think you want df.style.apply(... instead of just df.apply(... Commented Sep 4, 2021 at 8:09

1 Answer 1

2
  1. The asterisk needs to be escaped: '\*'
  2. The highlighting should be applied to df.style instead of just df
def highlight_(s, props=''):
    return np.where(s.str.contains('\*'), props, '')

df.style.apply(highlight_, props='background-color:yellow; color:black;')


To differentiate * and **, try np.select:

def highlight_(s):
    return np.select(
        condlist=[s.str.contains('\*\*'), s.str.contains('\*')],
        choicelist=['background-color:green', 'background-color:purple'],
        default='')

df.style.apply(highlight_)

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

2 Comments

Thanks for the suggestion @tdy. Bit greedy here, but can you suggest how can we have diffrent color for separate case of single and double *
@balandongiv see if the update works for you

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.