utf8编码在html输出,如何使用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

标签:python,unicode,pandas

来源: https://codeday.me/bug/20190628/1312408.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值