pandas 更改熊猫数据框中完整行的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49745256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:26:48  来源:igfitidea点击:

Change color of complete row in data frame in pandas

python-3.xpandas

提问by avinashse

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

我已经在 excel 文件上应用了Pandas,下面是数据框:

      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

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

我必须对上述数据框应用条件格式并转换为 html。

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

为此,我遵循了样式“ http://pandas.pydata.org/pandas-docs/stable/style.html#Building-Styles”,并在下面做了:

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

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

This is the output I am getting

这是我得到的输出

How can i get output like below ?

我怎样才能得到如下输出?

How can i output like this

我怎样才能像这样输出

回答by piRSquared

You use df.style.apply

你用 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)

enter image description here

在此处输入图片说明

回答by YOBEN_S

I think you can add one more condition here

我想你可以在这里再添加一个条件

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

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

enter image description here

在此处输入图片说明