将 pandas df写入csv时出现Unicode编码错误 [英] Unicode Encode Error when writing pandas df to csv

查看:118
本文介绍了将 pandas df写入csv时出现Unicode编码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我清理了400个excel文件,并使用熊猫将它们读入python,并将所有原始数据附加到一个大df中.

I cleaned 400 excel files and read them into python using pandas and appended all the raw data into one big df.

然后,当我尝试将其导出到csv时:

Then when I try to export it to a csv:

df.to_csv("path",header=True,index=False)

我收到此错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xc7' in position 20: ordinal not in range(128)

有人可以建议解决此问题的方法吗?

Can someone suggest a way to fix this and what it means?

谢谢

推荐答案

您的DataFrame中有unicode个值.文件存储字节,这意味着所有unicode必须先编码为字节,然后才能存储在文件中.您必须指定一种编码,例如utf-8.例如

You have unicode values in your DataFrame. Files store bytes, which means all unicode have to be encoded into bytes before they can be stored in a file. You have to specify an encoding, such as utf-8. For example,

df.to_csv('path', header=True, index=False, encoding='utf-8')

如果未指定编码,则df.to_csv使用的编码在Python2中默认为ascii,在Python3中默认为utf-8.

If you don't specify an encoding, then the encoding used by df.to_csv defaults to ascii in Python2, or utf-8 in Python3.

这篇关于将 pandas df写入csv时出现Unicode编码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆