如何使用utf-8编码将DataFrame导出到HTML?
问题内容:
我不断得到:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 265-266: ordinal not in range(128)
当我尝试:
df.to_html("mypage.html")
以下是如何重现该问题的示例:
df = pd.DataFrame({"a": [u'Rue du Gu\xc3\xa9, 78120 Sonchamp'], "b": [u"some other thing"]})
df.to_html("mypage.html")
中的元素列表"a"
类型为"unicode"
。
当我想将其导出到csv时,它可以工作,因为您可以执行以下操作:
df.to_csv("myfile.csv", encoding="utf-8")
问题答案:
您的问题出在其他代码中。示例代码具有Unicode字符串已被误解码为latin1
,Windows-1252
或类似的,由于其具有的UTF-8序列在它。在这里,我撤消了错误的解码并将其重新编码为UTF-8,但是您将要查找执行错误解码的位置:
>>> s = u'Rue du Gu\xc3\xa9, 78120 Sonchamp'
>>> s.encode('latin1').decode('utf8')
u'Rue du Gu\xe9, 78120 Sonchamp'
>>> print(s.encode('latin1').decode('utf8'))
Rue du Gué, 78120 Sonchamp