Python dataframe illegal character error into 'ascii' codec decode error

人走茶凉 提交于 2020-01-03 05:41:08

问题


I am attempting to write a pandas dataframe to excel. Initially, I received

openpyxl.utils.exceptions.IllegalCharacterError

which I resolved with:

def export_file(clients):

    clients = clients.applymap(lambda x: x.encode('unicode_escape').
             decode('utf-8') if isinstance(x, str) else x)

    clients.to_excel('all_clients.xlsx')

    return()

Which then resulted in:

 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128)

However, if i resolve the unicode error I get the initial pyxl error.

I seem to be unable to resolve one error without getting the opposing error. Any suggestions?


回答1:


Instead of writing directly using pandas, user xlsxwrite engine. This will resolve the errors.

writer = pd.ExcelWriter('all_clients.xlsx', engine='xlsxwriter') # engine is set here
clients.to_excel(writer,'Sheet1') # it is called here to write the excel sheet

openpyxl.utils.exceptions.IllegalCharacterError will be resolved.



来源:https://stackoverflow.com/questions/45312111/python-dataframe-illegal-character-error-into-ascii-codec-decode-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!