【问题标题】:Pandas dataframe with Greek characters to postgresql带有希腊字符的 Pandas 数据框到 postgresql
【发布时间】:2022-01-02 23:13:22
【问题描述】:

我正在处理以下内容: 蟒蛇 3.9.2 熊猫 1.3.4 PostgreSQL 14.1

我创建了一个示例数据框来探索 pandas 和 postgresql。

d = {'col1': ['Αθήνα', 'χαρύϊψχορες'], 'col2': ['Θεσσαλονίκη', 'Ξπφδ']}
df = pd.DataFrame(data=d)

当我调用 df 时在 Jypiter 上工作,我得到以下输出:

    col1    col2
0   Αθήνα   Θεσσαλονίκη
1   χαρύϊψχορες Ξπφδ

然后,我尝试使用以下代码将数据添加到 psql:

engine = create_engine('postgresql://user:password@localhost:port/test_db', encoding='utf-8-sig')
df.to_sql('sq_exp', engine)

如果我打开我的 CMD 来选择数据,我会得到这个错误:

test_db=# select * from sq_exp;
ERROR:  character with byte sequence 0xce 0x91 in encoding "UTF8" has no equivalent in encoding "WIN1252"

在尝试修复此错误时,我将编码设置为 win1252 只是为了得到相同的错误:

test_db=# SET client_encoding TO 'WIN1252';
SET
test_db=# select * from sq_exp;
ERROR:  character with byte sequence 0xce 0x91 in encoding "UTF8" has no equivalent in encoding "WIN1252"

按照 postgres 的文档,我将编码设置为 WIN1253 https://www.postgresql.org/docs/current/multibyte.html

当我选择数据时:select * from sq_exp; 我得到以下输出:

test_db=# select * from sq_exp;
 index |    col1     |    col2
-------+-------------+-------------
     0 | ┴Φ▐φß       | ╚σ≤≤ßδ∩φ▀Ωτ
     1 | ≈ß±²·°≈∩±σ≥ | ╬≡÷Σ

如您所见,这与最初创建的 df 完全不同,我尝试了多种方法来解决它。请有人指导我思考如何做到这一点?

非常感谢! [1]:https://i.stack.imgur.com/kkK3R.png [2]:https://i.stack.imgur.com/49rAe.png [3]:https://i.stack.imgur.com/8wIoq.png [4]:https://i.stack.imgur.com/IsHVM.png

【问题讨论】:

  • 你确定 PostgreSQL 9.3 吗?这是非常古老和过时的。你用的是什么版本?请不要使用图片,只需在您的问题中输入纯文本即可。
  • @FrankHeikens 感谢您的检查。你是对的,我已经用纯文本更新了这个问题。我使用的 PostgresSQL 版本是 14.1

标签: python sql pandas postgresql encoding


【解决方案1】:

我确实发现了这个问题。

CMD 似乎不支持希腊字符,这就是返回错误的原因:

ERROR:  character with byte sequence 0xce 0x91 in encoding "UTF8" has no equivalent in encoding "WIN1252"

解决方法实际上是在代码编辑器或数据库管理工具中查看您的数据。

这是一个使用 Visual Studio 代码的示例:

import psycopg2
conn_string = "host='localhost' dbname='database_name' user='postgres' password='password'"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("SELECT * FROM sq_exp")
records = cursor.fetchall()

运行上面的代码实际上会打印你预期的输出:

[(0, 'Αθήνα', 'Θεσσαλονίκη'), (1, 'χαρύϊψχορες', 'Ξπφδ')]

同样适用于使用数据库应用工具

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 2016-02-26
    相关资源
    最近更新 更多