Combining pandas "data frame.style" objects and outputting to html

Alex M picture Alex M · Feb 7, 2019 · Viewed 9.8k times · Source

I would like to combine pandas df.style objects that use the following methods - df.style.background_gradient and df.style.bar and export the result to html.

I'm successful when I have separate objects. Here is an example data frame:

df = pd.DataFrame(np.random.randn(15).reshape(5, 3))

I can then pass this to the different style methods:

# Use method "background_gradient"
styled_df_a = df.style.background_gradient(subset=[0, 1], 
                                       low=0, high=0.5, 
                                       cmap="YlGnBu")

# Use method "bar"
styled_df_b = df.style.bar(subset=[2], align='mid', 
                       color=['#d65f5f', '#5fba7d'])

I subsequently export each of the styled tables to html:

# Export styled table a to html
html = styled_df_a.render()
with open("df_a.html","w") as fp:
fp.write(html)

# Export styled table b to html
html = styled_df_b.render()
with open("df_b.html","w") as fp:
fp.write(html)  

I therefore have 2 html rendered styled tables. However, I would like to combine the 2 methods into 1 html styled table, such that columns 1-2 have the background_gradient styling and column 3 has the bar styling.

I tried this:

styled_df_c = styled_df_a.style.bar(subset=[2], align='mid', 
                                color=['#d65f5f', '#5fba7d'])

This doesn't work due to the following error:

AttributeError: 'Styler' object has no attribute 'style'

Is there a way to do this through some other means? I did try experimenting with the style.apply method of pandas but got a similar error as above.

Answer

Alex M picture Alex M · Feb 9, 2019

I've found a solution based on info here: mode.com/example-gallery/python_dataframe_styling

Rather than trying to coerce a styled object with more styling methods, you can simply pass multiple style methods to the same data frame simultaneously. Please see below:

# example data frame
df = pd.DataFrame(np.random.randn(15).reshape(5, 3))

# pass multiple style methods to same  data frame
styled_df = (df.style
             .background_gradient(subset=[0, 1], # background_gradient method
                                  low=0, high=0.5,
                                  cmap="YlGnBu")
             .bar(subset=[2], align='mid',       # bar method
                  color=['#d65f5f', '#5fba7d']))

# Export "styled_df" to html
html = styled_df.hide_index().render()
with open("html_c.html","w") as fp:
   fp.write(html)