[英]How to export DataFrame to Html with utf-8 encoding?
我不斷得到:
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字符串,由於其中包含UTF-8序列,因此被誤解碼為latin1
, Windows-1252
或類似名稱。 在這里,我撤消了錯誤的解碼,並將其重新編碼為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
問題實際上出在使用df.to_html("mypage.html")
直接將HTML保存到文件中。 相反,如果您自己編寫文件,則可以避免使用熊貓編碼錯誤。
html = df.to_html()
with open("mypage.html", "w", encoding="utf-8") as file:
file.write(html)
您可能還需要在HTML的開頭指定字符集,以使其在某些瀏覽器中正確顯示(HTML5默認為UTF-8):
<meta charset="UTF-8">
這是我所見過的唯一對我有用的方法。
它為我工作的方式:
html = df.to_html()
with open("dataframe.html", "w", encoding="utf-8") as file:
file.writelines('<meta charset="UTF-8">\n')
file.write(html)
如果確實需要將輸出保留為html,則可以在寫入to_html之前嘗試清除numpy數組中的代碼。
df = pd.DataFrame({"a": [u'Rue du Gu\xc3\xa9, 78120 Sonchamp'], "b": [u"some other thing"]})
def clean_unicode(df):
*#Transforms the DataFrame to Numpy array*
df=df.as_matrix()
*#Encode all strings with special characters*
for x in np.nditer(df, flags=['refs_ok'], op_flags =['copy', 'readonly']):
df[df==x]=str(str(x).encode("latin-1", "replace").decode('utf8'))
*#Transform the Numpy array to Dataframe again*
df=pd.DataFrame(df)
return df
df=clean_unicode(df)
df.to_html("Results.html') -----> Success!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.