[英]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
.要获得从红色到绿色的颜色范围,您可以使用 matplotlib
color maps
,更具体地说,是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.但在应用颜色映射之前,首先,您需要将
Opportunity
列中的数据标准化为 0 和 1 之间的值。然后,您可以从这里以您认为合适的任何方式将数据编码为颜色代码。 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.例如,我在这里使用 Pandas
apply
function 和rbg2hex
,目的是获取表示Opportunity
列中使用的颜色映射的 CSS 值。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.