0

I have a pandas dataframe and am trying to export this to excel file using pandas to_excel function.

I have written the code as below :

writer = pd.ExcelWriter(output_file_path, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False, encoding='utf-8')
writer.save()

Error : UnicodeDecodeError: 'ascii' codec can't decode byte 0x81 in position 23: ordinal not in range(128)

I have tried the below options and didn't get output.

1)

import sys  
reload(sys)  
sys.setdefaultencoding('utf8')

2)

def changeencode(data):
cols = data.columns
for col in cols:
if data[col].dtype == 'O':
    data[col] = data[col].str.decode('utf-8').str.encode('ascii', 'ignore')
return data  

Does anyone know any other solutions ?

Sindhu
  • 36
  • 3
  • does [this](https://stackoverflow.com/questions/54133455/importing-csv-using-pd-read-csv-invalid-start-byte-error/54134734#54134734) help? – anky Mar 21 '19 at 12:37
  • @anky_91 how to do this for writing to an excel file (to_excel)? – Sindhu Mar 21 '19 at 12:51

1 Answers1

0

You can set the default encoding to be Cp1252 and then try. That would work.

import sys
reload(sys)  
sys.setdefaultencoding('Cp1252')
Jim Todd
  • 1,488
  • 1
  • 11
  • 15
  • Still facing error : 'UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 23: character maps to ' . When i try to see sys.getdefaultencoding() i got 'ascii' – Sindhu Mar 21 '19 at 12:23