Pandas to_html()截断字符串内容

我有一个 PythonPandasDataFrame对象,其中包含文本数据。我的问题是,当我使用 to_html()函数时,它会截断输出中的字符串。

例如:

import pandas
df = pandas.DataFrame({'text': ['Lorem ipsum dolor sit amet, consectetur adipiscing elit.']})
print (df.to_html())

输出在 adapis...处被截断

<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>text</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td> Lorem ipsum dolor sit amet, consectetur adipis...</td>
</tr>
</tbody>
</table>

还有一个关于 SO 的相关问题,但是它使用占位符和搜索/替换功能来后处理 HTML,这是我想避免的:

这个问题有没有更简单的解决方案? 我找不到任何与 文件有关的东西。

28763 次浏览

What you are seeing is pandas truncating the output for display purposes only.

The default max_colwidth value is 50 which is what you are seeing.

You can set this value to whatever you desire or you can set it to -1 which effectively turns this off:

pd.set_option('display.max_colwidth', -1)

Although I would advise against this, it would be better to set it to something that can be displayed easily in your console or ipython.

A list of the options can be found here: http://pandas.pydata.org/pandas-docs/stable/options.html

it seems that pd.set_option('display.max_colwidth', -1) is indeed the only option. To prevent irreversible global changes of how dataframes are presented in the console, you may save the previous setting in a variable and restore it immediately after the usage, as follows:

    old_width = pd.get_option('display.max_colwidth')
pd.set_option('display.max_colwidth', -1)
open('some_file.html', 'w').write(some_data.to_html())
pd.set_option('display.max_colwidth', old_width)