【问题标题】:Is there any way to color code the data frame in Pandas? if condition match on one column then colorcode different column有什么方法可以对 Pandas 中的数据框进行颜色编码?如果一列的条件匹配,则对不同的列进行颜色编码
【发布时间】:2019-11-19 12:47:50
【问题描述】:

我在 pandas 中有一个数据框,其中包含多个列。如果条件与 C 列中的条件匹配,我的任务是对 A 列中的特定单元格进行颜色编码。 enter image description here

我附上了一个例子。 我想对 C 列应用三个不同的条件

 1. If Column C = poor than Column A = red color
 2. If Column C = good then Column A = Orange color
 3. If Column C = very good then Column A = Green color 

提前致谢!

【问题讨论】:

标签: python pandas dataframe styles


【解决方案1】:

Styler.applynumpy.select 一起用于按条件选择颜色的自定义函数:

df = pd.DataFrame({
         'A':[1,3,5,7],
         'B':list('abcd'),
         'C':['poor','good','very good','unknown'],

})
print (df)
   A  B          C
0  1  a       poor
1  3  b       good
2  5  c  very good
3  7  d    unknown

def color(x): 
   c1 = 'background-color: red'
   c2 = 'background-color: orange'
   c3 = 'background-color: green'
   c = 'background-color: '

   m1 = x['C'] == 'poor'
   m2 = x['C'] == 'good'
   m3 = x['C'] == 'very good'

   df = pd.DataFrame(c, index=x.index, columns=x.columns)
   df['A'] = np.select([m1, m2, m3], [c1, c2, c3], default=c)
   return df

df.style.apply(color,axis=None)

#if want output in excel file
#df.style.apply(color,axis=None).to_excel('styled.xlsx', engine='openpyxl', index=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2012-06-04
    • 2020-07-22
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多