我正尝试在Jupyter笔记本中显示一个包含多行文本列(例如代码片段)的DataFrame:
IPython.display.display(df)不幸的是,这并没有考虑到文本中的换行符,而是将每个单元格变成了一堵文本墙。
如何显示保留了文本单元格内换行符的数据帧?
发布于 2019-07-04 13:41:21
使用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-04-05 11:45:19
试试@unsorted对this question的回答
from IPython.display import display, HTML
def pretty_print(df):
return display( HTML( df.to_html().replace("\\n","<br>") ) )https://stackoverflow.com/questions/49661018
复制相似问题