使用 DataFrame 中的正确表示形式检查 \n(换行符)值

Review the \n (newline) values with proper representation in DataFrame

我有这个:

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

当我插入 DataFrame 时,它​​保持相同的方式:

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

        salute
0   hey\nthere

但我希望它能正确显示:

  salute
0 hey
  there

我该怎么做?

在 jupiter notebook 中工作时/google 可以使用 colab CSS 定制:

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

替代解决方案涉及用 br HTML 元素替换换行符:

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)