StyleΒΆ

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 pandas.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.

Contents

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.

The result of the function application, a CSS attribute-value pair, is stored in an internal dictionary on your Styler object.

Let's see some examples.

In [3]:
import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan

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

In [4]:
df.style
Out[4]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

Note: The DataFrame.style attribute is a propetry 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.

In [5]:
df.style.highlight_null().render().split('\n')[:10]
Out[5]:
['',
 '        <style  type="text/css" >',
 '        ',
 '        ',
 '            #T_3530213a_8d9b_11e5_b80c_a45e60bd97fbrow0_col2 {',
 '            ',
 '                background-color:  red;',
 '            ',
 '            }',
 '        ']

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 collied 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.

In [6]:
def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    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.

In [7]:
s = df.style.applymap(color_negative_red)
s
Out[7]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

Notice the similarity with the standard df.applymap, which operates on DataFrames elementwise. We want you to be able to resuse 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.

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.

In [8]:
def highlight_max(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]
In [9]:
df.style.apply(highlight_max)
Out[9]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

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

In [10]:
df.style.\
    applymap(color_negative_red).\
    apply(highlight_max)
Out[10]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.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.

In [11]:
def highlight_max(data, color='yellow'):
    '''
    highlight the maximum in a Series or DataFrame
    '''
    attr = 'background-color: {}'.format(color)
    if data.ndim == 1:  # Series from .apply(axis=0) or axis=1
        is_max = data == data.max()
        return [attr if v else '' for v in is_max]
    else:  # from .apply(axis=None)
        is_max = data == data.max().max()
        return pd.DataFrame(np.where(is_max, attr, ''),
                            index=data.index, columns=data.columns)
In [12]:
df.style.apply(highlight_max, color='darkorange', axis=None)
Out[12]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.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

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 simlar 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.

In [13]:
df.style.apply(highlight_max, subset=['B', 'C', 'D'])
Out[13]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

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

In [14]:
df.style.applymap(color_negative_red,
                  subset=pd.IndexSlice[2:5, ['B', 'D']])
Out[14]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.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.

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

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.

In [15]:
df.style.highlight_null(null_color='red')
Out[15]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

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

In [16]:
import seaborn as sns

cm = sns.light_palette("green", as_cmap=True)

s = df.style.background_gradient(cmap=cm)
s
Out[16]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.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.

In [17]:
# Uses the full color range
df.loc[:4].style.background_gradient(cmap='viridis')
Out[17]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
In [18]:
# Compreess the color range
(df.loc[:4]
    .style
    .background_gradient(cmap='viridis', low=.5, high=0)
    .highlight_null('red'))
Out[18]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018

You can include "bar charts" in your DataFrame.

In [19]:
df.style.bar(subset=['A', 'B'], color='#d65f5f')
Out[19]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

There's also .highlight_min and .highlight_max.

In [20]:
df.style.highlight_max(axis=0)
Out[20]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072
In [21]:
df.style.highlight_min(axis=0)
Out[21]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

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

In [22]:
df.style.set_properties(**{'background-color': 'black',
                           'color': 'lawngreen',
                           'border-color': 'white'})
Out[22]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072

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

In [23]:
df2 = -df
style1 = df.style.applymap(color_negative_red)
style1
Out[23]:
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072
In [24]:
style2 = df2.style
style2.use(style1.export())
style2
Out[24]:
A B C D E
0 -1.0 -1.329212 nan 0.31628 0.99081
1 -2.0 1.070816 1.438713 -0.564417 -0.295722
2 -3.0 1.626404 -0.219565 -0.678805 -1.889273
3 -4.0 -0.961538 -0.104011 0.481165 -0.850229
4 -5.0 -1.453425 -1.057737 -0.165562 -0.515018
5 -6.0 1.336936 -0.562861 -1.392855 0.063328
6 -7.0 -0.121668 -1.207603 0.00204 -1.627796
7 -8.0 -0.354493 -1.037528 0.385684 -0.519818
8 -9.0 -1.686583 1.325963 -1.428984 2.089354
9 -10.0 0.12982 -0.631523 0.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

Each of these can be specified in two ways:

  • A keyword argument to pandas.core.Styler
  • A call to one of the .set_ methods, e.g. .set_caption

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_ methods are more convenient.

Precision

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

In [25]:
with pd.option_context('display.precision', 2):
    html = (df.style
              .applymap(color_negative_red)
              .apply(highlight_max))
html
Out[25]:
A B C D E
0 1.0 1.33 nan -0.32 -0.99
1 2.0 -1.07 -1.44 0.56 0.3
2 3.0 -1.63 0.22 0.68 1.89
3 4.0 0.96 0.1 -0.48 0.85
4 5.0 1.45 1.06 0.17 0.52
5 6.0 -1.34 0.56 1.39 -0.06
6 7.0 0.12 1.21 -0.0 1.63
7 8.0 0.35 1.04 -0.39 0.52
8 9.0 1.69 -1.33 1.43 -2.09
9 10.0 -0.13 0.63 -0.59 0.29

Or through a set_precision method.

In [26]:
df.style\
  .applymap(color_negative_red)\
  .apply(highlight_max)\
  .set_precision(2)
Out[26]:
A B C D E
0 1.0 1.33 nan -0.32 -0.99
1 2.0 -1.07 -1.44 0.56 0.3
2 3.0 -1.63 0.22 0.68 1.89
3 4.0 0.96 0.1 -0.48 0.85
4 5.0 1.45 1.06 0.17 0.52
5 6.0 -1.34 0.56 1.39 -0.06
6 7.0 0.12 1.21 -0.0 1.63
7 8.0 0.35 1.04 -0.39 0.52
8 9.0 1.69 -1.33 1.43 -2.09
9 10.0 -0.13 0.63 -0.59 0.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.

In [27]:
df.style.set_caption('Colormaps, with a caption.')\
    .background_gradient(cmap=cm)
Out[27]:
Colormaps, with a caption.
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.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.

In [28]:
from IPython.display import HTML

def hover(hover_color="#ffff99"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])

styles = [
    hover(),
    dict(selector="th", props=[("font-size", "150%"),
                               ("text-align", "center")]),
    dict(selector="caption", props=[("caption-side", "bottom")])
]
html = (df.style.set_table_styles(styles)
          .set_caption("Hover to highlight."))
html
Out[28]:
Hover to highlight.
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.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.

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.

In [29]:
from IPython.html import widgets
@widgets.interact
def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0., 99.9), l=(0., 99.9)):
    return df.style.background_gradient(
        cmap=sns.palettes.diverging_palette(h_neg=h_neg, h_pos=h_pos, s=s, l=l,
                                            as_cmap=True)
    )
A B C D E
0 1.0 1.329212 nan -0.31628 -0.99081
1 2.0 -1.070816 -1.438713 0.564417 0.295722
2 3.0 -1.626404 0.219565 0.678805 1.889273
3 4.0 0.961538 0.104011 -0.481165 0.850229
4 5.0 1.453425 1.057737 0.165562 0.515018
5 6.0 -1.336936 0.562861 1.392855 -0.063328
6 7.0 0.121668 1.207603 -0.00204 1.627796
7 8.0 0.354493 1.037528 -0.385684 0.519818
8 9.0 1.686583 -1.325963 1.428984 -2.089354
9 10.0 -0.12982 0.631523 -0.586538 0.29072
In [30]:
def magnify():
    return [dict(selector="th",
                 props=[("font-size", "4pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]
In [31]:
np.random.seed(25)
cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)
df = pd.DataFrame(np.random.randn(20, 25)).cumsum()

df.style.background_gradient(cmap, axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '1pt'})\
    .set_caption("Hover to magify")\
    .set_precision(2)\
    .set_table_styles(magnify())
Out[31]:
Hover to magify
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
0 0.23 1.03 -0.84 -0.59 -0.96 -0.22 -0.62 1.84 -2.05 0.87 -0.92 -0.23 2.15 -1.33 0.08 -1.25 1.2 -1.05 1.06 -0.42 2.29 -2.59 2.82 0.68 -1.58
1 -1.75 1.56 -1.13 -1.1 1.03 0.0 -2.46 3.45 -1.66 1.27 -0.52 -0.02 1.52 -1.09 -1.86 -1.13 -0.68 -0.81 0.35 -0.06 1.79 -2.82 2.26 0.78 0.44
2 -0.65 3.22 -1.76 0.52 2.2 -0.37 -3.0 3.73 -1.87 2.46 0.21 -0.24 -0.1 -0.78 -3.02 -0.82 -0.21 -0.23 0.86 -0.68 1.45 -4.89 3.03 1.91 0.61
3 -1.62 3.71 -2.31 0.43 4.17 -0.43 -3.86 4.16 -2.15 1.08 0.12 0.6 -0.89 0.27 -3.67 -2.71 -0.31 -1.59 1.35 -1.83 0.91 -5.8 2.81 2.11 0.28
4 -3.35 4.48 -1.86 -1.7 5.19 -1.02 -3.81 4.72 -0.72 1.08 -0.18 0.83 -0.22 -1.08 -4.27 -2.88 -0.97 -1.78 1.53 -1.8 2.21 -6.34 3.34 2.49 2.09
5 -0.84 4.23 -1.65 -2.0 5.34 -0.99 -4.13 3.94 -1.06 -0.94 1.24 0.09 -1.78 -0.11 -4.45 -0.85 -2.06 -1.35 0.8 -1.63 1.54 -6.51 2.8 2.14 3.77
6 -0.74 5.35 -2.11 -1.13 4.2 -1.85 -3.2 3.76 -3.22 -1.23 0.34 0.57 -1.82 0.54 -4.43 -1.83 -4.03 -2.62 -0.2 -4.68 1.93 -8.46 3.34 2.52 5.81
7 -0.44 4.69 -2.3 -0.21 5.93 -2.63 -1.83 5.46 -4.5 -3.16 -1.73 0.18 0.11 0.04 -5.99 -0.45 -6.2 -3.89 0.71 -3.95 0.67 -7.26 2.97 3.39 6.66
8 0.92 5.8 -3.33 -0.65 5.99 -3.19 -1.83 5.63 -3.53 -1.3 -1.61 0.82 -2.45 -0.4 -6.06 -0.52 -6.6 -3.48 -0.04 -4.6 0.51 -5.85 3.23 2.4 5.08
9 0.38 5.54 -4.49 -0.8 7.05 -2.64 -0.44 5.35 -1.96 -0.33 -0.8 0.26 -3.37 -0.82 -6.05 -2.61 -8.45 -4.45 0.41 -4.71 1.89 -6.93 2.14 3.0 5.16
10 2.06 5.84 -3.9 -0.98 7.78 -2.49 -0.59 5.59 -2.22 -0.71 -0.46 1.8 -2.79 0.48 -5.97 -3.44 -7.77 -5.49 -0.7 -4.61 -0.52 -7.72 1.54 5.02 5.81
11 1.86 4.47 -2.17 -1.38 5.9 -0.49 0.02 5.78 -1.04 -0.6 0.49 1.96 -1.47 1.88 -5.92 -4.55 -8.15 -3.42 -2.24 -4.33 -1.17 -7.9 1.36 5.31 5.83
12 3.19 4.22 -3.06 -2.27 5.93 -2.64 0.33 6.72 -2.84 -0.2 1.89 2.63 -1.53 0.75 -5.27 -4.53 -7.57 -2.85 -2.17 -4.78 -1.13 -8.99 2.11 6.42 5.6
13 2.31 4.45 -3.87 -2.05 6.76 -3.25 -2.17 7.99 -2.56 -0.8 0.71 2.33 -0.16 -0.46 -5.1 -3.79 -7.58 -4.0 0.33 -3.67 -1.05 -8.71 2.47 5.87 6.71
14 3.78 4.33 -3.88 -1.58 6.22 -3.23 -1.46 5.57 -2.93 -0.33 -0.97 1.72 3.61 0.29 -4.21 -4.1 -6.68 -4.5 -2.19 -2.43 -1.64 -9.36 3.36 6.11 7.53
15 5.64 5.31 -3.98 -2.26 5.91 -3.3 -1.03 5.68 -3.06 -0.33 -1.16 2.19 4.2 1.01 -3.22 -4.31 -5.74 -4.44 -2.3 -1.36 -1.2 -11.27 2.59 6.69 5.91
16 4.08 4.34 -2.44 -3.3 6.04 -2.52 -0.47 5.28 -4.84 1.58 0.23 0.1 5.79 1.8 -3.13 -3.85 -5.53 -2.97 -2.13 -1.15 -0.56 -13.13 2.07 6.16 4.94
17 5.64 4.57 -3.53 -3.76 6.58 -2.58 -0.75 6.58 -4.78 3.63 -0.29 0.56 5.76 2.05 -2.27 -2.31 -4.95 -3.16 -3.06 -2.43 0.84 -12.57 3.56 7.36 4.7
18 5.99 5.82 -2.85 -4.15 7.12 -3.32 -1.21 7.93 -4.85 1.44 -0.63 0.35 7.47 0.87 -1.52 -2.09 -4.23 -2.55 -2.46 -2.89 1.9 -9.74 3.43 7.07 4.39
19 4.03 6.23 -4.1 -4.11 7.19 -4.1 -1.52 6.53 -5.21 -0.24 0.01 1.16 6.43 -1.97 -2.64 -1.66 -5.2 -3.25 -2.87 -1.65 1.64 -10.66 2.83 7.48 3.94

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

This section contains a bit of information about the implementation of Styler. Since the feature is so new all of this is subject to change, even more so than the end-use API.

As users apply styles (via .apply, .applymap or one of the builtins), we don't actually calculate anything. Instead, we append functions and arguments to a list self._todo. When asked (typically in .render we'll walk through the list and execute each function (this is in self._compute(). These functions update an internal defaultdict(list), self.ctx which maps DataFrame row / column positions to CSS attribute, value pairs.

We take the extra step through self._todo so that we can export styles and set them on other Stylers.

Rendering uses Jinja templates. The .translate method takes self.ctx and builds another dictionary ready to be passed into Styler.template.render, the Jinja template.

Alternate templates

We've used Jinja templates to build up the HTML. The template is stored as a class variable Styler.template.. Subclasses can override that.

class CustomStyle(Styler):
    template = Template("""...""")