Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 303
Daniel Mahler Avatar asked Dec 19 '22 00:12

Daniel Mahler


2 Answers

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

like image 114
yongjieyongjie Avatar answered Dec 26 '22 19:12

yongjieyongjie


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>") ) )
like image 28
Peter Leimbigler Avatar answered Dec 26 '22 18:12

Peter Leimbigler