'Add a new column for color code from red to green based on the increasing value of Opportunity in data frame

I have a data frame and I wanted to generate a new column for colour codes which stars from red for the least value of Opportunity and moves toward green for highest value of Opportunity

My Data Frame -

State       Brand       DYA  Opportunity    

Jharkhand   Ariel     0.15   0.00853    
Jharkhand   Fusion    0.02   0.00002
Jharkhand   Gillett   0.04   -0.0002


Solution 1:[1]

To obtain the color range from red to green you can use matplotlib color maps, more specifically, the RdYlGn. But before applying the color mapping, first, you need to normalize the data in the Opportunity column between 0 and 1. Then, from here you can encode the data to a color code in any away way you see appropriate. As an example, here I'm using Pandas apply function with the rbg2hex with the intention of grabbing the CSS value that represents the color mapping used in the Opportunity column.

import matplotlib.cm as cm
from matplotlib.colors import Normalize
from matplotlib.colors import rgb2hex

# df = Your original dataframe

cmapR = cm.get_cmap('RdYlGn')
norm = Normalize(vmin=df['Opportunity'].min(), vmax=df['Opportunity'].max())

df['Color'] = df['Opportunity'].apply(lambda r: rgb2hex(cmapR(norm(r))))

dstyle = df.style.background_gradient(cmap=cmapR, subset=['Opportunity'])
dstyle.to_html('sample.html')

df_color_coded

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 n1colas.m