Pretty printing newlines inside a string in a Pandas DataFrame Pretty printing newlines inside a string in a Pandas DataFrame python-3.x python-3.x

Pretty printing newlines inside a string in a Pandas DataFrame


If you're trying to do this in ipython notebook, you can do:

from IPython.display import display, HTMLdef pretty_print(df):    return display( HTML( df.to_html().replace("\\n","<br>") ) )


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

[For use in IPython notebooks]

Another way will be 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 DataFramedisplay(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 DataFramedisplay(df.style.set_properties(**{    'text-align': 'left',    'white-space': 'pre-wrap',})


Somewhat in line with unsorted's answer:

import pandas as pd# Save the original `to_html` function to call it laterpd.DataFrame.base_to_html = pd.DataFrame.to_html# Call it here in a controlled waypd.DataFrame.to_html = (    lambda df, *args, **kwargs:         (df.base_to_html(*args, **kwargs)           .replace(r"\n", "<br/>")))

This way, you don't need to call any explicit function in Jupyter notebooks, as to_html is called internally. If you want the original function, call base_to_html (or whatever you named it).

I'm using jupyter 1.0.0, notebook 5.7.6.