I'm working on a dataframe that I output to an html file. I would like to add colors to certain strings:
df1 = df1[(
df1['Visitor'].str.contains('^TOR|^MTL|^CGY|^WPG|^VAN|^EDM|^OTT', na=False)
) | (df1['Home'].str.contains('^TOR|^MTL|^CGY|^WPG|^VAN|^EDM|^OTT', na=False))]
df1.fillna('', inplace=True)
df1.to_html('schedule.html', index=False)
The above code removes all rows that don't contain any of the listed teams. I would like to add colors to the rows that are left by string. for example 'TOR'
would be colored blue.
As seen in another thread, this is what I tried but nothing changed:
def styler(col):
if col.name != 'Visitor vs Home':
return [''] * len(col)
bg_color = col.map({
'TOR': 'blue',
'MTL': 'red',
'VAN': 'green',
}).fillna('')
return 'background-color:' bg_color
df1.style.apply(styler)
Any tips or suggestions are very much welcome.
Thanks!
CodePudding user response:
Sample Data and imports:
import numpy as np
import pandas as pd
df = pd.DataFrame({
'Visitor': ['TOR', 'MTL', 'VAN', 'WPG', 'EDM'],
'Home': ['CGY', 'WPG', 'OTT', 'TOR', 'MTL'],
'Visitor vs Home': ['String with TOR',
'String with MTL',
'String with VAN',
'String with no match',
np.NaN]
})