根据数据框中 Opportunity 的递增值,为从红色到绿色的颜色代码添加一个新列

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

我有一个数据框,我想为颜色代码生成一个新列,该列从红色开始为 Opportunity 的最小值,向绿色移动以获得最高值 机会

我的数据框-

State       Brand       DYA  Opportunity    

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

要获得从红色到绿色的颜色范围,您可以将 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 函数与 rbg2hex 一起使用,目的是获取表示在中使用的颜色映射的 CSS 值Opportunity 列。

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')