5

I am trying to display a DataFrame with a mutiline text column (eg code snippet) in a Jupyter notebook:

IPython.display.display(df)

Unfortunatelly this does not respect the newlines in the text and turns each cell into a wall of text.

How can I display a dataframe with linebreaks within text cells preserved?

Daniel Mahler
  • 7,653
  • 5
  • 51
  • 90
  • Possible duplicate of [Pretty printing newlines inside a string in a Pandas DataFrame](https://stackoverflow.com/questions/34322448/pretty-printing-newlines-inside-a-string-in-a-pandas-dataframe) – Georgy Nov 23 '18 at 11:47

2 Answers2

11

Using pandas .set_properties() and CSS white-space property

My preferred way is to use pandas's pandas.io.formats.style.Styler.set_properties() method and the CSS "white-space": "pre-wrap" property:

from IPython.display import display

# Assuming the variable df contains the relevant DataFrame
display(df.style.set_properties(**{
    'white-space': 'pre-wrap',
})

To keep the text left-aligned, you might want to add 'text-align': 'left' as below:

from IPython.display import display

# Assuming the variable df contains the relevant DataFrame
display(df.style.set_properties(**{
    'text-align': 'left',
    'white-space': 'pre-wrap',
})

yongjieyongjie
  • 813
  • 10
  • 18
5

Try @unsorted's answer to this question:

from IPython.display import display, HTML
def pretty_print(df):
    return display( HTML( df.to_html().replace("\\n","<br>") ) )
Peter Leimbigler
  • 10,775
  • 1
  • 23
  • 37
  • 2
    Thanks! That does solve the newline problem, but it makes all the text lines right-justified again. I am currently using Styling (https://pandas.pydata.org/pandas-docs/stable/style.html) to force left justification. Is there a way to make the cells left justified with .to_html()? I see a way to make column headers left-justified, but not body cells. – Daniel Mahler Apr 05 '18 at 05:38