本文是小编为大家收集整理的关于如何使用lambda将样式应用于Pandas DataFrame?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
我有一个数据框架,我想突出显示" bbc"一词的细胞.
df.style.apply(lambda x: ["background-color: red" if x == "BBC News" else "background-color: green"])
或
df.style.apply(lambda x: ["background-color: red" if v == "BBC News" else "background-color: green" for v in x], axis=None)
,但这没有任何色彩. fwiw,我不知道我使用的示例中的x或v是什么.我假设x是一个单元格,v将是单元格的一部分?
我如何凝结格式化细胞?我还会添加其他人,即,如果" CNN"出现在单元格中,颜色黄色等.
编辑:我尝试了简单的df.style.apply(lambda x: ["background-color: green"]),什么也没发生(如果我使用#ff0000或rgb(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操作员允许您apply ["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)]到axis=1的每一行(由axis=1指定),其中x是您df的每个单独行.<<<<<<<<<<<<<<
在英语中,这意味着如果字符串'BBC'包含在x['newsSource']中,即'BBC',即'newsSource' 'newsSource' 'newsSource' 'newsSource' 'newsSource'的列.指定idx==0的额外逻辑仅表示该行x的第一个单元格,我们必须enumerate(x)才能跟踪当前列索引idx.否则,请勿使用else ""更改背景颜色.希望这很清楚!
其他推荐答案
让我知道是否有效?
def highlight_txt(s, txt): has_bbc = s.apply(lambda x: '') bbc = s.index.tolist().index('newsSource') has_bbc[bbc] = 'background-color: yellow' if txt in s[bbc] else 'background-color: green' return has_bbc df.style.apply(lambda x: highlight_txt(x, 'BBC', axis=1))
其他推荐答案
我将其与一个函数分开,以确保清晰,然后在行上迭代:
def highlight_cell(row): background = [] for cell in row: color = 'background-color: green' if 'BBC' in cell: color = 'background-color: red' elif 'CNN' in cell: color = 'background-color: yellow' background.append(color) return background df.style.apply(highlight_cell, axis=1)
问题描述
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!
其他推荐答案
Let me know if something like this works?
def highlight_txt(s, txt): has_bbc = s.apply(lambda x: '') bbc = s.index.tolist().index('newsSource') has_bbc[bbc] = 'background-color: yellow' if txt in s[bbc] else 'background-color: green' return has_bbc df.style.apply(lambda x: highlight_txt(x, 'BBC', axis=1))
其他推荐答案
I would separate this to a function for clarity, and then iterate over the rows:
def highlight_cell(row): background = [] for cell in row: color = 'background-color: green' if 'BBC' in cell: color = 'background-color: red' elif 'CNN' in cell: color = 'background-color: yellow' background.append(color) return background df.style.apply(highlight_cell, axis=1)