0

I have this:

test = ['hey\nthere']
Output: ['hey\nthere']

And when I insert in into the DataFrame it stays the same way:

test_pd = pd.DataFrame({'salute': test})
Output:

        salute
0   hey\nthere

But I want it to be shown properly:

  salute
0 hey
  there

How could I do this?

halfer
  • 19,824
  • 17
  • 99
  • 186
jose.gp
  • 122
  • 7
  • Possibly duplicate of https://stackoverflow.com/questions/34322448/pretty-printing-newlines-inside-a-string-in-a-pandas-dataframe – Daweo Oct 25 '20 at 07:59

1 Answers1

1

When working in jupiter notebook / google colab CSS customization can be used:

import pandas as pd
from IPython.display import display

test = ['hey\nthere']

test_pd = pd.DataFrame({'salute': test})

display(test_pd.style.set_properties(**{
    'white-space': 'pre-wrap'
}))

Alternative solution involves replacing newline character with br HTML element:

from IPython.display import display, HTML

test = ['hey\nthere']

test_pd = pd.DataFrame({'salute': test})

def pretty_print(df):
    return display( HTML( df.to_html().replace("\\n","<br>") ) )

pretty_print(test_pd)
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27