問題描述
我有一個包含文字資料的 Python Pandas DataFrame 物件。我的問題是,當我使用 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,我想避免:
這個問題有更簡單的解決方案嗎?我找不到與 documentation 相關的任何內容。
最佳解決思路
你看到的是 Pandas 截斷輸出僅用於顯示目的。
預設的 max_colwidth 值是 50,這是你看到的。
您可以將此值設定為任何您想要的值,也可以將其設定為-1,這有效地將其關閉:
pd.set_option('display.max_colwidth', -1)
雖然我建議反對這一點,但最好將其設定為可以在控制檯或 ipython 中輕鬆顯示的內容。
選項列表可以在這裡找到:http://pandas.pydata.org/pandas-docs/stable/options.html
次佳解決思路
似乎 pd.set_option('display.max_colwidth', -1)確實是唯一的選擇。為了防止在控制檯中顯示資料框的不可逆的全域性變化,您可以將以前的設定儲存在變數中,並在使用後立即恢復,如下所示:
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)
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。