Q:

How to use lambda to apply style to Pandas DataFrame

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.

A:

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!

