更改 pandas 数据框中完整行的颜色 [英] Change color of complete row in data frame in pandas

查看:133
本文介绍了更改 pandas 数据框中完整行的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在一个excel文件上应用了熊猫,下面是数据框:

I have applied pandas on an excel file and below is the dataframe :

      Name  Count
0   Name 1     75
1   Name 2     55
2   Name 3     50
3   Name 4     47
4   Name 5     43
5   Name 6     42
6   Name 7     35
7   Name 8     34
8   Name 9     32
9   Name 10    16
10  Name 11     6
11  Name 12     3
12  Name 13     1
13  Name 14     1
14    Total   440

我必须在上述数据框上应用条件格式,然后转换为html.

I have to apply conditional formatting on above data frame and convert in to html.

我遵循样式" http://pandas.pydata .org/pandas-docs/stable/style.html#Building-Styles 为此,并且在以下位置进行了操作:

I followed style "http://pandas.pydata.org/pandas-docs/stable/style.html#Building-Styles" for this and did below :

def change_colour(val):
   return ['background-color: red' if x < 40 else 'background-color: green' for x in val]

name_column_html_1 = final_name_df.style.apply(change_colour, axis=1, subset=['Count'])
print(name_column_html_1.render())

这是我从上面的代码中得到的输出

This is the output I am getting from above code

我如何获得如下所示的输出?

How can i get output like below ?

推荐答案

您使用df.style.apply

def row_style(row):
    if row.Name != 'Total':
        if row.Count < 40:
            return pd.Series('background-color: red', row.index)
        else:
            return pd.Series('background-color: green', row.index)
    else:
        return pd.Series('', row.index)

df.style.apply(row_style, axis=1)

这篇关于更改 pandas 数据框中完整行的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆