How to highlight particular cells in colour using groupby and styler

48 Views Asked by At

I have a df as follows

Group   Date    Data1   Data2
A   01-01-2023  22  23
A   01-02-2023  24  20
A   01-03-2023  10  20
A   01-04-2023  30  32
B   02-03-2023  24.5    26.5
B   02-04-2023  26.5    23.5
B   02-05-2023  12.5    23.5
B   02-06-2023  32.5    35.5
B   02-07-2023  27  30
B   02-08-2023  29  27

I have seperate list for group_A = [01-02-2023,01-04-2023] and group_B = [02-03-2023,02-08-2023].

These are the dates to be highlighted.

I tried using groupby and styler.

How to pass the list in groupby to styler and highlight the corrsponding date columns for both the groups.

1

There are 1 best solutions below

0
Smordy On

if i understood you correctly, you can do like this :

import pandas as pd

# Create the DataFrame
data = {
    'Group': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B'],
    'Date': ['01-01-2023', '01-02-2023', '01-03-2023', '01-04-2023', '02-03-2023', '02-04-2023', '02-05-2023', '02-06-2023', '02-07-2023', '02-08-2023'],
    'Data1': [22, 24, 10, 30, 24.5, 26.5, 12.5, 32.5, 27, 29],
    'Data2': [23, 20, 20, 32, 26.5, 23.5, 23.5, 35.5, 30, 27]
}

df = pd.DataFrame(data)

# Define the highlight function
def highlight_dates(date):
    return ['background-color: yellow' if date in group_A else 'background-color: cyan' if date in group_B else '' for date in df['Date']]

# Specify the groups
group_A = ['01-02-2023', '01-04-2023']
group_B = ['02-03-2023', '02-08-2023']

# Apply the styling
styled_df = df.style.apply(highlight_dates, axis=0, subset=['Date'])

# Display the styled DataFrame
styled_df