0

I have a dataframe that looks like this:

names=pd.Dataframe({'name': ['ben','adam','steve'],
'name1':['ben1','adam1','steve1'],
'name2':['ben2','adam2','steve2'],
'name3':['ben3','adam3','steve3'],
'name1_comp':[1,0,1],
'name2_comp':[0,1,1],
'name3_comp':[0,1,1]}]

I would like an output of :

names=pd.Dataframe({'name': ['ben','adam','steve'],
'name1':['ben1','adam1','steve1'],
'name2':['ben2','adam2','steve2'],
'name3':['ben3','adam3','steve3']}]

with ben1, adam2, adam3, steve1,steve2,steve3 highlighted. This will be written into excel afterwards.

How would I go about doing this? Thanks

3
  • The names you want to be highlighted do not match the boolean table provided (ben3 should not be highlighted, should it?) Commented Jun 8, 2022 at 9:18
  • Thanks for pointing that out. I've edited the question Commented Jun 8, 2022 at 9:23
  • so, "highlighting" here means the cells should be coloured differently in the exported excel file? Commented Jun 8, 2022 at 9:50

1 Answer 1

1

You can use:

names2 = names.filter(like='_comp').rename(columns=lambda x: x[:-5])

def hl(df):
    style = 'background-color: yellow'
    return np.where(names2.reindex_like(df).eq(1), style, '')

names.filter(regex=r'(?<!_comp)$').style.apply(hl, axis=None)

output:

enter image description here

For the full DataFrame:

def hl(df):
    style = 'background-color: yellow'
    df2 = df.filter(like='_comp').rename(columns=lambda x: x[:-5]).reindex_like(df)
    return np.where(df2.eq(1), style, '')

names.style.apply(hl, axis=None)

output:

enter image description here

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

7 Comments

After using your code, I get an error saying that "Function <function hl at 0x7f16c24da550> must return a dataFrame when passed to 'Styler.apply' with axis=None"
which pandas version do you have? Try: names2.reindex_like(df).eq(1).map({True: style, False: ''})/return df2.eq(1).map({True: style, False: ''})
I am using python 3 on a jupyter notebook. The fix you suggested doesn't seem to work either.
I'm talking about the pandas version: pd.__version__
Oops sorry misread your comment. 1.0.5
|

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.