![](/img/trans.png)
[英]How to convert SQL Oracle Database into a Pandas DataFrame?
[英]Convert Pandas DataFrame WITHOUT connecting to a SQL database
我見過的所有解決方案都需要連接到 SQL 數據庫,這不是這個問題的目標。
假設我有一個簡單的 pandas DataFrame:
df = pd.DataFrame({{'hello'}:[1], {'world}:[2]})
...我想自動將其轉換為可以執行以生成表的 .sql 文件,例如:
#psuedocode
py_script.output_file_sql('my_table')
return """CREATE TABLE my_table (
hello integer,
world integer
);""
在沒有實際連接到數據庫的情況下,我找不到將 pandas 轉換為 an.sql 的文檔。
如果我使用 sqlalchemy,則使用 information_schema.columns 或 \d table_name 運行查詢似乎不起作用。
有什么建議么?
你需要 map 正確的所有數據類型,我只用了一個例子來告訴你如何開始。
但要正確,如果您想擁有所有選項,則需要重建所有https://www.postgresql.org/docs/current/sql-createtable.html
所以我重復我的評論,最好是使用備份工具在數據庫服務器上備份數據庫,然后改用 hat。
import pandas as pd
df = pd.DataFrame({'hello':[1], 'world':[2]})
df.name = 'Ones'
indextext = "hello"
def typeconversion(x):
return {
'int64': 'bigint ',
'float64': 'FLOAT'
}[x]
def get_sql(df,Indexx_table):
STR_sql = "CREATE TABLE " + df.name + "( "
for (col1, col2) in zip(df.columns, df.dtypes):
STR_sql += col1 + " " + typeconversion(col2.name) + ','
#remove last comma
STR_sql = STR_sql[:-1]
if Indexx_table:
STR_sql += ", PRIMARY KEY (" + Indexx_table + ")"
STR_sql += ")"
return STR_sql
print(get_sql(df,indextext))
結果是
CREATE TABLE Ones( hello bigint ,world bigint , PRIMARY KEY (hello))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.