在 Pandas DataFrame 的文本列中显示嵌入的换行符

Dan*_*ler 3 formatting ipython dataframe pandas jupyter-notebook

我正在尝试在 Jupyter 笔记本中显示带有多行文本列(例如代码片段)的 DataFrame:

IPython.display.display(df)
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不尊重文本中的换行符,并将每个单元格变成了一堵文本墙。

如何在保留的文本单元格中显示带有换行符的数据框?

Pet*_*ler 5

尝试@unsorted对此问题的回答:

from IPython.display import display, HTML
def pretty_print(df):
    return display( HTML( df.to_html().replace("\\n","<br>") ) )
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这确实解决了换行问题,但它使所有文本行再次右对齐。我目前正在使用样式(https://pandas.pydata.org/pandas-docs/stable/style.html)强制左对齐。有没有办法用 .to_html() 使单元格左对齐?我看到了一种使列标题左对齐的方法,但不是正文单元格。 (2认同)

yon*_*jie 5

使用 pandas.set_properties()和 CSSwhite-space属性

我的首选方法是使用 pandas 的pandas.io.formats.style.Styler.set_properties()方法和 CSS"white-space": "pre-wrap"属性:

from IPython.display import display

# Assuming the variable df contains the relevant DataFrame
display(df.style.set_properties(**{
    'white-space': 'pre-wrap',
})

Run Code Online (Sandbox Code Playgroud)

要保持文本左对齐,您可能需要添加'text-align': 'left'如下内容:

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

Run Code Online (Sandbox Code Playgroud)