Skip to content Skip to sidebar Skip to footer

Highlight Dataframe Cells Based On Multiple Conditions In Python

Given a small dataset as follows: id room area situation 0 1 A-102 world under construction 1 2 NaN 24 under construction 2 3 B309 NaN

Solution 1:

Idea is to create customized function for return DataFrame of styles and reuse m1, m2, m3 boolean masks:

m1 = df.room.str.match('^[a-zA-Z\d\-]*$', na = False)
m2 = df.area.str.contains('^\d+$', na = True)
m3 = df.situation.str.contains('under decoration', na = False)
a = np.where(m1, None, 'incorrect room name')
b = np.where(m2, None, 'area is not a numbers')  
c = np.where(m3, 'decoration is in the content', None) 


f = (lambda x: '; '.join(y for y in x if pd.notna(y)) 
                if any(pd.notna(np.array(x))) else np.nan )
df['check'] = [f(x) for x in zip(a, b, c)]
print(df)


def highlight(x):
    c1 = 'background-color: yellow'

    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1['room'] = np.where(m1, '', c1)
    df1['area'] = np.where(m2, '', c1)
    df1['situation'] = np.where(m3, c1, '')
    # print(df1)
    return df1

df.style.apply(highlight, axis = None).to_excel('test.xlsx', index = False)

Post a Comment for "Highlight Dataframe Cells Based On Multiple Conditions In Python"