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?
.set_properties()
and CSS white-space
propertyMy 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',
})
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>") ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With