Answer a question

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:

  • Can I set variable column widths in pandas?
    will truncate column widths, but will not affect the title and will not wrap the text
  • Pretty printing newlines inside a string in a Pandas DataFrame
    This again touches on column contents but not the title

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

Answers

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

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐