Search code examples
pythonpandasdataframeformattingjupyter-notebook

Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks


I have long titles for some of my columns in my data frame, and I would like the ability to wrap the text. I know that this functionality is built into pandas, as I do:

pd.DataFrame(np.random.randn(2, 10), 
    columns=['Very Long Column Title ' + str(i) for i in range(10)])

DataFrame with wrapped column names

But if I have fewer columns, the titles will not wrap:

pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long Column Title ' + str(i) for i in range(2)])

DataFrame does not wrap column names

I have also tried to manually insert a newline:

import pandas as pd    
pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long \n Column Title ' + str(i) for i in range(2)])

But that gives the same output as above.

I've found similar for answers on this topic:

I am working in a Jupyter notebook, but would prefer a pandas-based solution, if possible.


Solution

  • 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')])])