Python MySQL编码错误: 'latin-1' codec can't encode character: ordinal not in range(256)

标签 python mysql pandas

我在 Python 中被 UnicodeEncodeError 困住了一段时间。

这就是我正在做的事情:

  1. 我根据各种分析创建了一个数据框。数据框总共有 30 列,包含多种类型的值(intstringdatetime 等)。
  2. 我创建了到 Azure 中已安装 MySQL 的远程实例的 SSH 连接。我使用 SQLAlchemy 创建连接。
  3. 我运行 df.to_sql 命令并收到以下错误

UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2013' in position 8: ordinal not in range(256)

我尝试这样做,但似乎不起作用。

engine = create_engine('mysql+pymysql://user:pwd@host:%s/db?charset=utf8' % server.local_bind_port)

我已阅读here我可以使用u.encode('latin-1', 'replace')。但是我是否需要执行该操作并遍历每个 String 列并对其进行编码?或者还有什么我可以做的吗?

最佳答案

这是我想出的解决方案。

我创建了一个函数来对数据中的不同字符进行编码。

def custom_encoder(x):
    #Check if the value is Unicode
    if type(x)==type(u''):
        return x.encode('utf8','ignore')
    else:
        return x

I 循环遍历所有列并对所有值进行编码。此后,MySQL允许数据写入。

关于Python MySQL编码错误: 'latin-1' codec can't encode character: ordinal not in range(256),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44319141/

相关文章:

python - 如何使用 pandas 数据框有效更新 mysql 表?

python - 发送在 Python 中压缩的 zip 存档但尝试在 Rust 中解压缩的问题

python - GCS 实体的 blob_key 以后可以安全使用吗?

mysql - 如何按最佳匹配排序

mysql - Codeigniter,使用的SELECT语句具有不同的列数

pandas - 如何通过分组来填充 NaN?

python - 不间断地将对象添加到队列中

python - win32剪贴板不存在?

mysql - 如何对mysql中相似的条目组执行平均

python - 计算 Pandas 每一列的有效方法?