How to alternate colours everytime my value changes in a specific column?

51 views Asked by At

I want to switch the colour of my entire row everytime the value in column 'column2' changes.

Here is an example of how I am trying it to look like:

enter image description here

If it helps here is my dataframe:

df1 = pd.DataFrame([
    ['A1',  'B2',  'C1',   'D1'],
    ['A2',  'B2',  'C2',   'D2'],
    ['A3',  'B2',  'C3',   'D3'],
    ['A4',  'B4',  'C4',   'D4'],
    ['A5',  'B4',  'C5',   'D5'],
    ['A6',  'B4',  'C6',   'D6'],
    ['A7',  'B6',  'C7',   'D7'],
    ['A8',  'B6',  'C8',   'D8'],
    ['A9',  'B10', 'C9',   'D9'],
    ['A10', 'B10', 'C10',  'D10'],
    ['A11', 'B10', 'C11',  'D11'],
    ['A12', 'B10', 'C12',  'D12'],
    ['A13', 'B14', 'C13',  'D13'],
    ['A14', 'B14', 'C14',  'D14'],
    ['A15', 'B14', 'C15',  'D15']], 
   columns=['column1', 'column2', 'column3', 'column4']) 
1

There are 1 answers

0
jlandercy On BEST ANSWER

Something like:

keys = df["c2"].unique().tolist()
color = df["c2"].apply(lambda x: keys.index(x) % 2)
color = color.replace({0: 'background-color: green', 1: ''})
df.style.apply(lambda x: color)

Should do the trick:

enter image description here