如何使用Lambda将样式应用于Pandas DataFrame [英] How to use lambda to apply style to Pandas DataFrame

查看:363
本文介绍了如何使用Lambda将样式应用于Pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想用红色突出显示出现"BBC"字样的单元格.

查看此SO线程

df.style.apply(lambda x: ["background-color: red" if v == "BBC News" else "background-color: green" for v in x], axis=None)

但这不会使任何颜色变色. FWIW,我不知道我使用的示例中的xv是什么.我假设x是一个单元格,而v将是该单元格的一部分?

如何确定单元格的格式?我还会添加其他内容,例如,如果"CNN"出现在单元格中,颜色为黄色等.

我只是尝试了df.style.apply(lambda x: ["background-color: green"])而没有任何反应(与使用#ff0000rgb(0,0,255)相同).

明确地说,我正在做

df.style.apply(lambda x: ["background-color: #ff0000" if v['newsSource'] == "BBC News" else "background-color: #ffff00"], axis=None)
df.to_html("styletest.html")

因此,我希望在 HTML文档 中显示颜色,而不一定是数据框本身.

解决方案

好的,应该这样做:

import pandas as pd

df = pd.DataFrame([['BBC News','something','Test1'],
                    ['The Wall Street Journal','something else','Test2'],
                    ['BBC News','something else entirely','Test3']],
                    columns=['newsSource','description','title'])

html = df.style.apply(lambda x: ["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)], axis = 1).set_table_attributes('border="1" class="dataframe table table-hover table-bordered"').render()

with open('test.html', 'w') as f:
    f.write(html)

说明:

lambda运算符允许您将["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)]以下["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)]df的每一行(由axis=1指定),其中xdf的每一行. /p>

在英语中,这意味着如果字符串'BBC'包含在x['newsSource']中,即df行的'newsSource'列的'newsSource'列,则更改为"background: red".指定idx==0的额外逻辑仅意味着该行x的第一个单元格,为了跟踪当前列索引idx,我们必须对此行进行enumerate(x).否则,请勿使用else ""更改背景颜色.希望这很清楚!

I have a dataframe, and I would like to highlight the cells red, where the word "BBC" appears.

Looking at this SO thread and this one I tried the below:

df.style.apply(lambda x: ["background-color: red" if x == "BBC News" else "background-color: green"])

or

df.style.apply(lambda x: ["background-color: red" if v == "BBC News" else "background-color: green" for v in x], axis=None)

But this doesn't color anything. FWIW, I don't know what the x or v are in the examples I used. I assume x is a cell, and v would be a part of the cell?

How can I conditinally format cells? I'd also be adding others, i.e. if "CNN" appears in a cell, color yellow, etc.

Edit: I tried simply df.style.apply(lambda x: ["background-color: green"]) and nothing happened (same if I used #ff0000 or rgb(0,0,255)).

To be explicit, I'm doing:

df.style.apply(lambda x: ["background-color: #ff0000" if v['newsSource'] == "BBC News" else "background-color: #ffff00"], axis=None)
df.to_html("styletest.html")

So I want the coloring visible in the HTML DOCUMENT not the dataframe itself necessarily.

解决方案

Alright, this should do it:

import pandas as pd

df = pd.DataFrame([['BBC News','something','Test1'],
                    ['The Wall Street Journal','something else','Test2'],
                    ['BBC News','something else entirely','Test3']],
                    columns=['newsSource','description','title'])

html = df.style.apply(lambda x: ["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)], axis = 1).set_table_attributes('border="1" class="dataframe table table-hover table-bordered"').render()

with open('test.html', 'w') as f:
    f.write(html)

Explanation:

The lambda operator allows you to apply the following ["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)]to every row of your df (specified by axis=1), where x is each individual row of your df.

In English, this means change to "background: red" if the string 'BBC' is contained in x['newsSource'], i.e. the 'newsSource' column of the row x of df. The extra logic specifying idx==0 means only the first cell of that row x, for which we have to enumerate(x) in order to track the current column index idx. Otherwise, do not change the background color, using else "". Hope that's clear!

这篇关于如何使用Lambda将样式应用于Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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