In this short post, we will see how to use set_properties to change display options like:

  • column width
  • color
  • column size
  • etc

in Pandas DataFrame. We will show also methods like:

  • set_table_attributes
  • set_table_styles
  • set_caption

Setup

Suppose we have DataFrame like:

import pandas as pd

data = {
    'amount': [10.00, 20.5, 17.34],
    'url': ['https://datascientyst.com/', 
            'https://datascientyst.com/pandas-most-typical-errors-and-solutions/', 
            'https://datascientyst.com/pandas-show-all-columns-rows/'],
}
df = pd.DataFrame(data)

with data(showing truncated data like Jupyter):

amount url
0 10.00 https://datascientyst.com/
1 20.50 https://datascientyst.com/pandas-most-typical-...
2 17.34 https://datascientyst.com/pandas-show-all-colu...

Displaying data in JupyterLab or Notebook will truncate the long strings by default.

If we use styler for this DataFrame like:

df.style.background_gradient(cmap='Greens')

Then full width of the columns is displayed like:

amount url
0 10.00 https://datascientyst.com/
1 20.50 https://datascientyst.com/pandas-most-typical-errors-and-solutions/
2 17.34 https://datascientyst.com/pandas-show-all-columns-rows/

1. Change display option of Styler

Trying to change display options of Pandas like explained in: How to show all columns and rows in Pandas - by using pd.set_option('display.max_rows', None) will not work.

In order to change display options for Pandas styler we can:

  • create new column with shorter width
  • use .set_properties() to change table properties like column width

Changing display option for a the whole DataFrame styler

df.style.background_gradient(cmap='Greens').set_properties(**{'max-width': '200px'})  

or we can use subset of column for which to change the table properties:

df.style.background_gradient(cmap='Greens').set_properties(subset=['url'], **{'max-width': '200px'})  

2. Pandas set_table_attributes

We can change more options by using method: set_table_attributes:

styler1.set_table_attributes('style="font-size: 25px"')

3. Pandas set_table_styles

Another option is to use method: set_table_styles to change how Pandas styler is displayed in Jupyter:

styler1.set_table_styles([{'selector': '*', 'props': 
                          [('color', 'black'),('border-style','solid'),('border-width','1px')]},
                        {'selector': 'th', 'props': 
                          [('background-color',  color1)]}])

4. Combine multiple styles

We can combine multiple methods at once to achieve nicer styling like:

  • Set DataFrame caption
  • change font size on DataFrame display
styler0.set_table_attributes("style='display:inline;font-size: 25px;'").set_caption('Before')

Conclusion

In this article we saw how to change display options for Pandas Styler. We discussed multiple ways to change table properties for DataFrames.

Finally we can achieve very beautiful DataFrame outlooks like shown on the image below: