【问题标题】:displaying embedded newlines in a text column of a Pandas DataFrame在 Pandas DataFrame 的文本列中显示嵌入的换行符
【发布时间】:2018-09-14 14:33:20
【问题描述】:

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

IPython.display.display(df)

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

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

【问题讨论】:

标签: pandas dataframe formatting ipython jupyter-notebook


【解决方案1】:

尝试@unsorted 对this question 的回答:

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

【讨论】:

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

使用 pandas .set_properties() 和 CSS white-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',
})

要保持文本左对齐,您可能需要添加'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',
})

【讨论】:

  • 看起来不错。我需要把它弄出来
猜你喜欢
  • 2018-10-22
  • 1970-01-01
  • 2018-11-01
  • 2015-05-12
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 2019-12-29
  • 2013-03-01
相关资源
最近更新 更多