簡體   English   中英

Pandas dataframe 與希臘字符到 postgresql

[英]Pandas dataframe with Greek characters to postgresql

我正在使用以下產品:Python 3.9.2 Pandas 1.3.4 PostgreSQL 14.1

我創建了一個示例 dataframe 來探索 pandas 和 postgresql。

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

當我調用 df 時在 Jypiter 上工作,我得到以下 output:

    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 到 select 數據,我得到這個錯誤:

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數據: select * from sq_exp; 我得到以下 output:

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/49rAe.png [3]: Z5E056C50BADE5018044 i.stack.imgur.com/8wIoq.png [4]: https://i.stack.imgur.com/IsHVM.png

我實際上已經發現了這個問題。

似乎 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()

運行上面的代碼實際上會打印出預期的 output:

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

使用數據庫應用程序工具也是如此

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM