0

I want to print my pandas dataframes with newline characters actually being new lines. I can use the following code but it's quite verbose.

How can I set this globally, i.e., for this jupyter notebook?

df = pd.DataFrame({
    'data': ['Laughing\nIs\nGood\nFor\nYou']
})

# Shows newline characters as '\n'
display(df)

# Actually prints new lines but is quite verbose
display(df.style.set_properties(**{
    'text-align': 'left',
    'white-space': 'pre-wrap',
}))
codeananda
  • 939
  • 1
  • 10
  • 16
  • You can make it less verbose by exporting the style and using it again, see [Sharing Styles](https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Sharing-styles). Or you can try overriding internals, like [here](https://stackoverflow.com/a/58922866/8508004). – Wayne Nov 03 '22 at 16:25

1 Answers1

0

Illustrating with code adapted from OP code my comment about the use of Sharing styles to export a style and use again to be less verbose:

import pandas as pd
df = pd.DataFrame({
    'data': ['Laughing\nIs\nGood\nFor\nYou']
})

# Shows newline characters as '\n'
display(df)

my_df_styled=df.style.set_properties(**{
    'text-align': 'left',
    'white-space': 'pre-wrap',
})
display(my_df_styled)

###-------above inherited from OP code--------###

df2 = pd.DataFrame({
    'data': ['Trombones\nCan\nAlso\nBe\nGood\nFor\nYou']
})
df2_styled=df2.style.use(my_df_styled.export())
display(df2_styled)
display(df2)
Wayne
  • 6,607
  • 8
  • 36
  • 93