0

Let's say I have a dataframe like the following;

df = pd.DataFrame({'Sample': ['A', 'B', 'C', 'D','E','F'],
                    'NFW': [8.16, 8.63, 9.25, 8.97, 7.5, 8.21],
                    'Qubit': [55, 100, 229, 30, 42, 33],
                    'Lane': ['1', '1', '2', '2', '3', '3']})

I want to colorize the background of all rows based on the values of the Lane column dynamically. Also, I'll write this dataframe to an excel file and I need to keep all style changes in there too.

2
  • What means dynamically ? Commented Sep 21, 2022 at 11:07
  • I mean I don't want to assign colors for each value the Lane column can get. So maybe a color palette I can use to colorize the rows. Commented Sep 21, 2022 at 11:14

1 Answer 1

1

IIUC, you can use a colormap (for example from ) and map it to each row using a Categorical and style.apply:

import matplotlib

cmap = matplotlib.cm.get_cmap('Pastel1')
colors = [matplotlib.colors.rgb2hex(cmap(i)) for i in range(cmap.N)]
# ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd', '#fddaec', '#f2f2f2']

def color(df, colors=colors):
    # get unique values as category
    s = df['Lane'].astype('category')
    # map the colors and create CSS string
    s = ('background-color: '
         +s.cat.rename_categories(colors[:len(s.cat.categories)])
           .astype(str)
        )
    # expand to DataFrame size
    return pd.DataFrame(np.tile(s, (df.shape[1], 1)).T,
                        index=df.index, columns=df.columns)
    
df.style.apply(color, axis=None)

enter image description here

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

Comments

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.