Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks

Here is an answer that does not involve changing the IPython properties:

df = pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long Column Title ' + str(i) for i in range(2)])
df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])

Jupyter notebooks inherit their display properties from a number of sources. There is no property in pandas that restricts the width of the column headers because pandas is not what causes the text to wrap, it is actually the rendered HTML.

You can overwrite the default Jupyter Notebook styles to restrict the maximum width of the table headers using:

from IPython.core.display import HTML
HTML("<style>.rendered_html th {max-width: 120px;}</style>")

Run this code once at the top of your notebook to set the max column width of html table headers to 120 pixels.


Alternatively, you could use the package textwrap:

import textwrap

cols = ['Very Long Column Title ' + str(i) for i in range(2)]

# Split wide columns, you can then join these with any delimiter you'd like
cols = [textwrap.wrap(x, width=20) for x in cols]

# print(cols)
# [['Very Long Column', 'Title 0'], ['Very Long Column', 'Title 1']]