Daniel Mahler
Daniel Mahler

Reputation: 8203

displaying embedded newlines in a text column of a Pandas DataFrame

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?

Upvotes: 5

Views: 6509

Answers (2)

yongjieyongjie
yongjieyongjie

Reputation: 893

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',
})

Upvotes: 11

Peter Leimbigler
Peter Leimbigler

Reputation: 11105

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>") ) )

Upvotes: 5

Related Questions