How to export DataFrame to Html with utf-8 encoding?

后端 未结 4 1437
南笙
南笙 2021-01-05 05:39

I keep getting:

UnicodeEncodeError: \'ascii\' codec can\'t encode characters in position 265-266: ordinal not in range(128)

when I try:

4条回答
  •  再見小時候
    2021-01-05 06:23

    If you really need to keep the output to html, you could try cleaning the code in a numpy array before writing to_html.

    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!
    

提交回复
热议问题