6

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?

1

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

That looks great. I need to rry it out
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>") ) )

1 Comment

Thanks! That does solve the newline problem, but it makes all the text lines right-justified again. I am currently using Styling (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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.