简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM