Styling

New in version 0.17.1

Provisional: This is a new feature and still under development. We’ll be adding features and possibly making breaking changes in future releases. We’d love to hear your feedback.

This document is written as a Jupyter Notebook, and can be viewed or downloaded here.

You can apply conditional formatting, the visual styling of a DataFrame depending on the data within, by using the DataFrame.style property. This is a property that returns a Styler object, which has useful methods for formatting and displaying DataFrames.

The styling is accomplished using CSS. You write “style functions” that take scalars, DataFrames or Series, and return like-indexed DataFrames or Series with CSS "attribute: value" pairs for the values. These functions can be incrementally passed to the Styler which collects the styles before rendering.

Building styles

Pass your style functions into one of the following methods:

  • Styler.applymap: elementwise
  • Styler.apply: column-/row-/table-wise

Both of those methods take a function (and some other keyword arguments) and applies your function to the DataFrame in a certain way. Styler.applymap works through the DataFrame elementwise. Styler.apply passes each column or row into your DataFrame one-at-a-time or the entire table at once, depending on the axis keyword argument. For columnwise use axis=0, rowwise use axis=1, and for the entire table at once use axis=None.

For Styler.applymap your function should take a scalar and return a single string with the CSS attribute-value pair.

For Styler.apply your function should take a Series or DataFrame (depending on the axis parameter), and return a Series or DataFrame with an identical shape where each value is a string with a CSS attribute-value pair.

Let’s see some examples.

  1. [2]:
  1. import pandas as pd
  2. import numpy as np
  3.  
  4. np.random.seed(24)
  5. df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
  6. df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
  7. axis=1)
  8. df.iloc[0, 2] = np.nan

Here’s a boring example of rendering a DataFrame, without any (visible) styles:

  1. [3]:
  1. df.style
  1. [3]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Note: The DataFrame.style attribute is a property that returns a Styler object. Styler has a repr_html method defined on it so they are rendered automatically. If you want the actual HTML back for further processing or for writing to file call the .render() method which returns a string.

The above output looks very similar to the standard DataFrame HTML representation. But we’ve done some work behind the scenes to attach CSS classes to each cell. We can view these by calling the .render method.

  1. [4]:
  1. df.style.highlight_null().render().split('\n')[:10]
  1. [4]:
  1. ['<style type="text/css" >',
  2. ' #T_93f7fcb8_032a_11ea_87a9_6fa86878a2d6row0_col2 {',
  3. ' background-color: red;',
  4. ' }</style><table id="T_93f7fcb8_032a_11ea_87a9_6fa86878a2d6" ><thead> <tr> <th class="blank level0" ></th> <th class="col_heading level0 col0" >A</th> <th class="col_heading level0 col1" >B</th> <th class="col_heading level0 col2" >C</th> <th class="col_heading level0 col3" >D</th> <th class="col_heading level0 col4" >E</th> </tr></thead><tbody>',
  5. ' <tr>',
  6. ' <th id="T_93f7fcb8_032a_11ea_87a9_6fa86878a2d6level0_row0" class="row_heading level0 row0" >0</th>',
  7. ' <td id="T_93f7fcb8_032a_11ea_87a9_6fa86878a2d6row0_col0" class="data row0 col0" >1</td>',
  8. ' <td id="T_93f7fcb8_032a_11ea_87a9_6fa86878a2d6row0_col1" class="data row0 col1" >1.32921</td>',
  9. ' <td id="T_93f7fcb8_032a_11ea_87a9_6fa86878a2d6row0_col2" class="data row0 col2" >nan</td>',
  10. ' <td id="T_93f7fcb8_032a_11ea_87a9_6fa86878a2d6row0_col3" class="data row0 col3" >-0.31628</td>']

The row0_col2 is the identifier for that particular cell. We’ve also prepended each row/column identifier with a UUID unique to each DataFrame so that the style from one doesn’t collide with the styling from another within the same notebook or page (you can set the uuid if you’d like to tie together the styling of two DataFrames).

When writing style functions, you take care of producing the CSS attribute / value pairs you want. Pandas matches those up with the CSS classes that identify each cell.

Let’s write a simple style function that will color negative numbers red and positive numbers black.

  1. [5]:
  1. def color_negative_red(val):
  2. """
  3. Takes a scalar and returns a string with
  4. the css property `'color: red'` for negative
  5. strings, black otherwise.
  6. """
  7. color = 'red' if val < 0 else 'black'
  8. return 'color: %s' % color

In this case, the cell’s style depends only on it’s own value. That means we should use the Styler.applymap method which works elementwise.

  1. [6]:
  1. s = df.style.applymap(color_negative_red)
  2. s
  1. [6]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Notice the similarity with the standard df.applymap, which operates on DataFrames elementwise. We want you to be able to reuse your existing knowledge of how to interact with DataFrames.

Notice also that our function returned a string containing the CSS attribute and value, separated by a colon just like in a <style> tag. This will be a common theme.

Finally, the input shapes matched. Styler.applymap calls the function on each scalar input, and the function returns a scalar output.

Now suppose you wanted to highlight the maximum value in each column. We can’t use .applymap anymore since that operated elementwise. Instead, we’ll turn to .apply which operates columnwise (or rowwise using the axis keyword). Later on we’ll see that something like highlight_max is already defined on Styler so you wouldn’t need to write this yourself.

  1. [7]:
  1. def highlight_max(s):
  2. '''
  3. highlight the maximum in a Series yellow.
  4. '''
  5. is_max = s == s.max()
  6. return ['background-color: yellow' if v else '' for v in is_max]
  1. [8]:
  1. df.style.apply(highlight_max)
  1. [8]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

In this case the input is a Series, one column at a time. Notice that the output shape of highlight_max matches the input shape, an array with len(s) items.

We encourage you to use method chains to build up a style piecewise, before finally rending at the end of the chain.

  1. [9]:
  1. df.style.\
  2. applymap(color_negative_red).\
  3. apply(highlight_max)
  1. [9]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Above we used Styler.apply to pass in each column one at a time.

Debugging Tip: If you’re having trouble writing your style function, try just passing it into DataFrame.apply. Internally, Styler.apply uses DataFrame.apply so the result should be the same.

What if you wanted to highlight just the maximum value in the entire table? Use .apply(function, axis=None) to indicate that your function wants the entire table, not one column or row at a time. Let’s try that next.

We’ll rewrite our highlight-max to handle either Series (from .apply(axis=0 or 1)) or DataFrames (from .apply(axis=None)). We’ll also allow the color to be adjustable, to demonstrate that .apply, and .applymap pass along keyword arguments.

  1. [10]:
  1. def highlight_max(data, color='yellow'):
  2. '''
  3. highlight the maximum in a Series or DataFrame
  4. '''
  5. attr = 'background-color: {}'.format(color)
  6. if data.ndim == 1: # Series from .apply(axis=0) or axis=1
  7. is_max = data == data.max()
  8. return [attr if v else '' for v in is_max]
  9. else: # from .apply(axis=None)
  10. is_max = data == data.max().max()
  11. return pd.DataFrame(np.where(is_max, attr, ''),
  12. index=data.index, columns=data.columns)

When using Styler.apply(func, axis=None), the function must return a DataFrame with the same index and column labels.

  1. [11]:
  1. df.style.apply(highlight_max, color='darkorange', axis=None)
  1. [11]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Building Styles Summary

Style functions should return strings with one or more CSS attribute: value delimited by semicolons. Use

  • Styler.applymap(func) for elementwise styles
  • Styler.apply(func, axis=0) for columnwise styles
  • Styler.apply(func, axis=1) for rowwise styles
  • Styler.apply(func, axis=None) for tablewise styles

And crucially the input and output shapes of func must match. If x is the input then func(x).shape == x.shape.

Finer control: slicing

Both Styler.apply, and Styler.applymap accept a subset keyword. This allows you to apply styles to specific rows or columns, without having to code that logic into your style function.

The value passed to subset behaves similar to slicing a DataFrame.

  • A scalar is treated as a column label
  • A list (or series or numpy array)
  • A tuple is treated as (row_indexer, column_indexer)

Consider using pd.IndexSlice to construct the tuple for the last one.

  1. [12]:
  1. df.style.apply(highlight_max, subset=['B', 'C', 'D'])
  1. [12]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

For row and column slicing, any valid indexer to .loc will work.

  1. [13]:
  1. df.style.applymap(color_negative_red,
  2. subset=pd.IndexSlice[2:5, ['B', 'D']])
  1. [13]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Only label-based slicing is supported right now, not positional.

If your style function uses a subset or axis keyword argument, consider wrapping your function in a functools.partial, partialing out that keyword.

  1. my_func2 = functools.partial(my_func, subset=42)

Finer Control: Display Values

We distinguish the display value from the actual value in Styler. To control the display value, the text is printed in each cell, use Styler.format. Cells can be formatted according to a format spec string or a callable that takes a single value and returns a string.

  1. [14]:
  1. df.style.format("{:.2%}")
  1. [14]:
ABCDE
0100.00%132.92%nan%-31.63%-99.08%
1200.00%-107.08%-143.87%56.44%29.57%
2300.00%-162.64%21.96%67.88%188.93%
3400.00%96.15%10.40%-48.12%85.02%
4500.00%145.34%105.77%16.56%51.50%
5600.00%-133.69%56.29%139.29%-6.33%
6700.00%12.17%120.76%-0.20%162.78%
7800.00%35.45%103.75%-38.57%51.98%
8900.00%168.66%-132.60%142.90%-208.94%
91000.00%-12.98%63.15%-58.65%29.07%

Use a dictionary to format specific columns.

  1. [15]:
  1. df.style.format({'B': "{:0<4.0f}", 'D': '{:+.2f}'})
  1. [15]:
ABCDE
011000nan-0.32-0.99081
12-100-1.43871+0.560.295722
23-2000.219565+0.681.88927
3410000.104011-0.480.850229
4510001.05774+0.170.515018
56-1000.562861+1.39-0.063328
6700001.2076-0.001.6278
7800001.03753-0.390.519818
892000-1.32596+1.43-2.08935
910-0000.631523-0.590.29072

Or pass in a callable (or dictionary of callables) for more flexible handling.

  1. [16]:
  1. df.style.format({"B": lambda x: "±{:.2f}".format(abs(x))})
  1. [16]:
ABCDE
01±1.33nan-0.31628-0.99081
12±1.07-1.438710.5644170.295722
23±1.630.2195650.6788051.88927
34±0.960.104011-0.4811650.850229
45±1.451.057740.1655620.515018
56±1.340.5628611.39285-0.063328
67±0.121.2076-0.002040211.6278
78±0.351.03753-0.3856840.519818
89±1.69-1.325961.42898-2.08935
910±0.130.631523-0.5865380.29072

Builtin styles

Finally, we expect certain styling functions to be common enough that we’ve included a few “built-in” to the Styler, so you don’t have to write them yourself.

  1. [17]:
  1. df.style.highlight_null(null_color='red')
  1. [17]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

You can create “heatmaps” with the background_gradient method. These require matplotlib, and we’ll use Seaborn to get a nice colormap.

  1. [18]:
  1. import seaborn as sns
  2.  
  3. cm = sns.light_palette("green", as_cmap=True)
  4.  
  5. s = df.style.background_gradient(cmap=cm)
  6. s
  1. /opt/conda/envs/pandas/lib/python3.7/site-packages/matplotlib/colors.py:527: RuntimeWarning: invalid value encountered in less
  2. xa[xa < 0] = -1
  1. [18]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Styler.background_gradient takes the keyword arguments low and high. Roughly speaking these extend the range of your data by low and high percent so that when we convert the colors, the colormap’s entire range isn’t used. This is useful so that you can actually read the text still.

  1. [19]:
  1. # Uses the full color range
  2. df.loc[:4].style.background_gradient(cmap='viridis')
  1. [19]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
  1. [20]:
  1. # Compress the color range
  2. (df.loc[:4]
  3. .style
  4. .background_gradient(cmap='viridis', low=.5, high=0)
  5. .highlight_null('red'))
  1. [20]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018

There’s also .highlight_min and .highlight_max.

  1. [21]:
  1. df.style.highlight_max(axis=0)
  1. [21]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Use Styler.set_properties when the style doesn’t actually depend on the values.

  1. [22]:
  1. df.style.set_properties(**{'background-color': 'black',
  2. 'color': 'lawngreen',
  3. 'border-color': 'white'})
  1. [22]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Bar charts

You can include “bar charts” in your DataFrame.

  1. [23]:
  1. df.style.bar(subset=['A', 'B'], color='#d65f5f')
  1. [23]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

New in version 0.20.0 is the ability to customize further the bar chart: You can now have the df.style.bar be centered on zero or midpoint value (in addition to the already existing way of having the min value at the left side of the cell), and you can pass a list of [color_negative, color_positive].

Here’s how you can change the above with the new align='mid' option:

  1. [24]:
  1. df.style.bar(subset=['A', 'B'], align='mid', color=['#d65f5f', '#5fba7d'])
  1. [24]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

The following example aims to give a highlight of the behavior of the new align options:

  1. [25]:
  1. import pandas as pd
  2. from IPython.display import HTML
  3.  
  4. # Test series
  5. test1 = pd.Series([-100,-60,-30,-20], name='All Negative')
  6. test2 = pd.Series([10,20,50,100], name='All Positive')
  7. test3 = pd.Series([-10,-5,0,90], name='Both Pos and Neg')
  8.  
  9. head = """
  10. <table>
  11. <thead>
  12. <th>Align</th>
  13. <th>All Negative</th>
  14. <th>All Positive</th>
  15. <th>Both Neg and Pos</th>
  16. </thead>
  17. </tbody>
  18.  
  19. """
  20.  
  21. aligns = ['left','zero','mid']
  22. for align in aligns:
  23. row = "<tr><th>{}</th>".format(align)
  24. for serie in [test1,test2,test3]:
  25. s = serie.copy()
  26. s.name=''
  27. row += "<td>{}</td>".format(s.to_frame().style.bar(align=align,
  28. color=['#d65f5f', '#5fba7d'],
  29. width=100).render()) #testn['width']
  30. row += '</tr>'
  31. head += row
  32.  
  33. head+= """
  34. </tbody>
  35. </table>"""
  36.  
  37.  
  38. HTML(head)
  1. [25]:
AlignAll NegativeAll PositiveBoth Neg and Pos
left
0-100
1-60
2-30
3-20

010
120
250
3100

0-10
1-5
20
390

zero

0-100
1-60
2-30
3-20

010
120
250
3100

0-10
1-5
20
390

mid

0-100
1-60
2-30
3-20

010
120
250
3100

0-10
1-5
20
390

Sharing styles

Say you have a lovely style built up for a DataFrame, and now you want to apply the same style to a second DataFrame. Export the style with df1.style.export, and import it on the second DataFrame with df1.style.set

  1. [26]:
  1. df2 = -df
  2. style1 = df.style.applymap(color_negative_red)
  3. style1
  1. [26]:
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072
  1. [27]:
  1. style2 = df2.style
  2. style2.use(style1.export())
  3. style2
  1. [27]:
ABCDE
0-1-1.32921nan0.316280.99081
1-21.070821.43871-0.564417-0.295722
2-31.6264-0.219565-0.678805-1.88927
3-4-0.961538-0.1040110.481165-0.850229
4-5-1.45342-1.05774-0.165562-0.515018
5-61.33694-0.562861-1.392850.063328
6-7-0.121668-1.20760.00204021-1.6278
7-8-0.354493-1.037530.385684-0.519818
8-9-1.686581.32596-1.428982.08935
9-100.12982-0.6315230.586538-0.29072

Notice that you’re able share the styles even though they’re data aware. The styles are re-evaluated on the new DataFrame they’ve been used upon.

Other Options

You’ve seen a few methods for data-driven styling. Styler also provides a few other options for styles that don’t depend on the data.

  • precision
  • captions
  • table-wide styles
  • hiding the index or columns

Each of these can be specified in two ways:

  • A keyword argument to Styler.init
  • A call to one of the .set or .hide methods, e.g. .set_caption or .hide_columns

The best method to use depends on the context. Use the Styler constructor when building many styled DataFrames that should all share the same properties. For interactive use, the.set and .hide methods are more convenient.

Precision

You can control the precision of floats using pandas’ regular display.precision option.

  1. [28]:
  1. with pd.option_context('display.precision', 2):
  2. html = (df.style
  3. .applymap(color_negative_red)
  4. .apply(highlight_max))
  5. html
  1. [28]:
ABCDE
011.3nan-0.32-0.99
12-1.1-1.40.560.3
23-1.60.220.681.9
340.960.1-0.480.85
451.51.10.170.52
56-1.30.561.4-0.063
670.121.2-0.0021.6
780.351-0.390.52
891.7-1.31.4-2.1
910-0.130.63-0.590.29

Or through a set_precision method.

  1. [29]:
  1. df.style\
  2. .applymap(color_negative_red)\
  3. .apply(highlight_max)\
  4. .set_precision(2)
  1. [29]:
ABCDE
011.3nan-0.32-0.99
12-1.1-1.40.560.3
23-1.60.220.681.9
340.960.1-0.480.85
451.51.10.170.52
56-1.30.561.4-0.063
670.121.2-0.0021.6
780.351-0.390.52
891.7-1.31.4-2.1
910-0.130.63-0.590.29

Setting the precision only affects the printed number; the full-precision values are always passed to your style functions. You can always use df.round(2).style if you’d prefer to round from the start.

Captions

Regular table captions can be added in a few ways.

  1. [30]:
  1. df.style.set_caption('Colormaps, with a caption.')\
  2. .background_gradient(cmap=cm)
  1. [30]:
Colormaps, with a caption.
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Table styles

The next option you have are “table styles”. These are styles that apply to the table as a whole, but don’t look at the data. Certain sytlings, including pseudo-selectors like :hover can only be used this way.

  1. [31]:
  1. from IPython.display import HTML
  2.  
  3. def hover(hover_color="#ffff99"):
  4. return dict(selector="tr:hover",
  5. props=[("background-color", "%s" % hover_color)])
  6.  
  7. styles = [
  8. hover(),
  9. dict(selector="th", props=[("font-size", "150%"),
  10. ("text-align", "center")]),
  11. dict(selector="caption", props=[("caption-side", "bottom")])
  12. ]
  13. html = (df.style.set_table_styles(styles)
  14. .set_caption("Hover to highlight."))
  15. html
  1. [31]:
Hover to highlight.
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

table_styles should be a list of dictionaries. Each dictionary should have the selector and props keys. The value for selector should be a valid CSS selector. Recall that all the styles are already attached to an id, unique to each Styler. This selector is in addition to that id. The value for props should be a list of tuples of ('attribute', 'value').

table_styles are extremely flexible, but not as fun to type out by hand. We hope to collect some useful ones either in pandas, or preferable in a new package that builds on top the tools here.

Hiding the Index or Columns

The index can be hidden from rendering by calling Styler.hide_index. Columns can be hidden from rendering by calling Styler.hide_columns and passing in the name of a column, or a slice of columns.

  1. [32]:
  1. df.style.hide_index()
  1. [32]:
ABCDE
11.32921nan-0.31628-0.99081
2-1.07082-1.438710.5644170.295722
3-1.62640.2195650.6788051.88927
40.9615380.104011-0.4811650.850229
51.453421.057740.1655620.515018
6-1.336940.5628611.39285-0.063328
70.1216681.2076-0.002040211.6278
80.3544931.03753-0.3856840.519818
91.68658-1.325961.42898-2.08935
10-0.129820.631523-0.5865380.29072
  1. [33]:
  1. df.style.hide_columns(['C','D'])
  1. [33]:
ABE
011.32921-0.99081
12-1.070820.295722
23-1.62641.88927
340.9615380.850229
451.453420.515018
56-1.33694-0.063328
670.1216681.6278
780.3544930.519818
891.68658-2.08935
910-0.129820.29072

CSS classes

Certain CSS classes are attached to cells.

  • Index and Column names include index_name and level<k> where k is its level in a MultiIndex
  • Index label cells include
    • row_heading
    • row<n> where n is the numeric position of the row
    • level<k> where k is the level in a MultiIndex
  • Column label cells include
    • col_heading
    • col<n> where n is the numeric position of the column
    • level<k> where k is the level in a MultiIndex
  • Blank cells include blank
  • Data cells include data

Limitations

  • DataFrame only (use Series.to_frame().style)
  • The index and columns must be unique
  • No large repr, and performance isn’t great; this is intended for summary DataFrames
  • You can only style the values, not the index or columns
  • You can only apply styles, you can’t insert new HTML entities

Some of these will be addressed in the future.

Terms

  • Style function: a function that’s passed into Styler.apply or Styler.applymap and returns values like 'css attribute: value'
  • Builtin style functions: style functions that are methods on Styler
  • table style: a dictionary with the two keys selector and props. selector is the CSS selector that props will apply to. props is a list of (attribute, value) tuples. A list of table styles passed into Styler.

Fun stuff

Here are a few interesting examples.

Styler interacts pretty well with widgets. If you’re viewing this online instead of running the notebook yourself, you’re missing out on interactively adjusting the color palette.

  1. [34]:
  1. from IPython.html import widgets
  2. @widgets.interact
  3. def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0., 99.9), l=(0., 99.9)):
  4. return df.style.background_gradient(
  5. cmap=sns.palettes.diverging_palette(h_neg=h_neg, h_pos=h_pos, s=s, l=l,
  6. as_cmap=True)
  7. )
ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072
  1. [35]:
  1. def magnify():
  2. return [dict(selector="th",
  3. props=[("font-size", "4pt")]),
  4. dict(selector="td",
  5. props=[('padding', "0em 0em")]),
  6. dict(selector="th:hover",
  7. props=[("font-size", "12pt")]),
  8. dict(selector="tr:hover td:hover",
  9. props=[('max-width', '200px'),
  10. ('font-size', '12pt')])
  11. ]
  1. [36]:
  1. np.random.seed(25)
  2. cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)
  3. bigdf = pd.DataFrame(np.random.randn(20, 25)).cumsum()
  4.  
  5. bigdf.style.background_gradient(cmap, axis=1)\
  6. .set_properties(**{'max-width': '80px', 'font-size': '1pt'})\
  7. .set_caption("Hover to magnify")\
  8. .set_precision(2)\
  9. .set_table_styles(magnify())
  1. [36]:
Hover to magnify
0123456789101112131415161718192021222324
00.231-0.84-0.59-0.96-0.22-0.621.8-2.10.87-0.92-0.232.2-1.30.076-1.21.2-11.1-0.422.3-2.62.80.68-1.6
1-1.71.6-1.1-1.110.0037-2.53.4-1.71.3-0.52-0.0151.5-1.1-1.9-1.1-0.68-0.810.35-0.0551.8-2.82.30.780.44
2-0.653.2-1.80.522.2-0.37-33.7-1.92.50.21-0.24-0.1-0.78-3-0.82-0.21-0.230.86-0.681.4-4.931.90.61
3-1.63.7-2.30.434.2-0.43-3.94.2-2.11.10.120.6-0.890.27-3.7-2.7-0.31-1.61.4-1.80.91-5.82.82.10.28
4-3.34.5-1.9-1.75.2-1-3.84.7-0.721.1-0.180.83-0.22-1.1-4.3-2.9-0.97-1.81.5-1.82.2-6.33.32.52.1
5-0.844.2-1.7-25.3-0.99-4.13.9-1.1-0.941.20.087-1.8-0.11-4.5-0.85-2.1-1.40.8-1.61.5-6.52.82.13.8
6-0.745.4-2.1-1.14.2-1.8-3.23.8-3.2-1.20.340.57-1.80.54-4.4-1.8-4-2.6-0.2-4.71.9-8.53.32.55.8
7-0.444.7-2.3-0.215.9-2.6-1.85.5-4.5-3.2-1.70.180.110.036-6-0.45-6.2-3.90.71-3.90.67-7.333.46.7
80.925.8-3.3-0.656-3.2-1.85.6-3.5-1.3-1.60.82-2.4-0.4-6.1-0.52-6.6-3.5-0.043-4.60.51-5.83.22.45.1
90.385.5-4.5-0.87.1-2.6-0.445.3-2-0.33-0.80.26-3.4-0.82-6.1-2.6-8.5-4.50.41-4.71.9-6.92.135.2
102.15.8-3.9-0.987.8-2.5-0.595.6-2.2-0.71-0.461.8-2.80.48-6-3.4-7.8-5.5-0.7-4.6-0.52-7.71.555.8
111.94.5-2.2-1.45.9-0.490.0175.8-1-0.60.492-1.51.9-5.9-4.5-8.2-3.4-2.2-4.3-1.2-7.91.45.35.8
123.24.2-3.1-2.35.9-2.60.336.7-2.8-0.21.92.6-1.50.75-5.3-4.5-7.6-2.9-2.2-4.8-1.1-92.16.45.6
132.34.5-3.9-26.8-3.3-2.28-2.6-0.80.712.3-0.16-0.46-5.1-3.8-7.6-40.33-3.7-1-8.72.55.96.7
143.84.3-3.9-1.66.2-3.2-1.55.6-2.9-0.33-0.971.73.60.29-4.2-4.1-6.7-4.5-2.2-2.4-1.6-9.43.46.17.5
155.65.3-4-2.35.9-3.3-15.7-3.1-0.33-1.22.24.21-3.2-4.3-5.7-4.4-2.3-1.4-1.2-112.66.75.9
164.14.3-2.4-3.36-2.5-0.475.3-4.81.60.230.0995.81.8-3.1-3.9-5.5-3-2.1-1.1-0.56-132.16.24.9
175.64.6-3.5-3.86.6-2.6-0.756.6-4.83.6-0.290.565.82-2.3-2.3-5-3.2-3.1-2.40.84-133.67.44.7
1865.8-2.8-4.27.1-3.3-1.27.9-4.91.4-0.630.357.50.87-1.5-2.1-4.2-2.5-2.5-2.91.9-9.73.47.14.4
1946.2-4.1-4.17.2-4.1-1.56.5-5.2-0.240.00721.26.4-2-2.6-1.7-5.2-3.3-2.9-1.71.6-112.87.53.9

Export to Excel

New in version 0.20.0

Experimental: This is a new feature and still under development. We’ll be adding features and possibly making breaking changes in future releases. We’d love to hear your feedback.

Some support is available for exporting styled DataFrames to Excel worksheets using the OpenPyXL or XlsxWriter engines. CSS2.2 properties handled include:

  • background-color
  • border-style, border-width, border-color and their {top, right, bottom, left variants}
  • color
  • font-family
  • font-style
  • font-weight
  • text-align
  • text-decoration
  • vertical-align
  • white-space: nowrap
  • Only CSS2 named colors and hex colors of the form #rgb or #rrggbb are currently supported.
  • The following pseudo CSS properties are also available to set excel specific style properties:
    • number-format
  1. [37]:
  1. df.style.\
  2. applymap(color_negative_red).\
  3. apply(highlight_max).\
  4. to_excel('styled.xlsx', engine='openpyxl')

A screenshot of the output:

Excel spreadsheet with styled DataFrame

Extensibility

The core of pandas is, and will remain, its “high-performance, easy-to-use data structures”. With that in mind, we hope that DataFrame.style accomplishes two goals

  • Provide an API that is pleasing to use interactively and is “good enough” for many tasks
  • Provide the foundations for dedicated libraries to build on

If you build a great library on top of this, let us know and we’ll link to it.

Subclassing

If the default template doesn’t quite suit your needs, you can subclass Styler and extend or override the template. We’ll show an example of extending the default template to insert a custom header before each table.

  1. [38]:
  1. from jinja2 import Environment, ChoiceLoader, FileSystemLoader
  2. from IPython.display import HTML
  3. from pandas.io.formats.style import Styler

We’ll use the following template:

  1. [39]:
  1. with open("templates/myhtml.tpl") as f:
  2. print(f.read())
  1. {% extends "html.tpl" %}
  2. {% block table %}
  3. <h1>{{ table_title|default("My Table") }}</h1>
  4. {{ super() }}
  5. {% endblock table %}
  6.  

Now that we’ve created a template, we need to set up a subclass of Styler that knows about it.

  1. [40]:
  1. class MyStyler(Styler):
  2. env = Environment(
  3. loader=ChoiceLoader([
  4. FileSystemLoader("templates"), # contains ours
  5. Styler.loader, # the default
  6. ])
  7. )
  8. template = env.get_template("myhtml.tpl")

Notice that we include the original loader in our environment’s loader. That’s because we extend the original template, so the Jinja environment needs to be able to find it.

Now we can use that custom styler. It’s init takes a DataFrame.

  1. [41]:
  1. MyStyler(df)
  1. [41]:

My Table

ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Our custom template accepts a table_title keyword. We can provide the value in the .render method.

  1. [42]:
  1. HTML(MyStyler(df).render(table_title="Extending Example"))
  1. [42]:

Extending Example

ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

For convenience, we provide the Styler.from_custom_template method that does the same as the custom subclass.

  1. [43]:
  1. EasyStyler = Styler.from_custom_template("templates", "myhtml.tpl")
  2. EasyStyler(df)
  1. [43]:

My Table

ABCDE
011.32921nan-0.31628-0.99081
12-1.07082-1.438710.5644170.295722
23-1.62640.2195650.6788051.88927
340.9615380.104011-0.4811650.850229
451.453421.057740.1655620.515018
56-1.336940.5628611.39285-0.063328
670.1216681.2076-0.002040211.6278
780.3544931.03753-0.3856840.519818
891.68658-1.325961.42898-2.08935
910-0.129820.631523-0.5865380.29072

Here’s the template structure:

  1. [44]:
  1. with open("templates/template_structure.html") as f:
  2. structure = f.read()
  3.  
  4. HTML(structure)
  1. [44]:

before_style

style

  1. <style type="text/css">

table_styles

before_cellstyle

cellstyle

  1. </style>

before_table

table

  1. <table ...>

caption

theadbefore_head_rows

head_tr (loop over headers)

after_head_rows

tbodybefore_rows

tr (loop over data rows)

after_rows

  1. </table>

after_table

See the template in the GitHub repo for more details.