使用 Python 将 Excel 数据插入 Postgres
Inserting Excel Data into Postgres with Python
有一个包含约 20.000 行数据的工作表,将这些数据插入 postgres 数据库的最佳方法是什么?
我将在其中插入数据的 table 包含许多外键,这意味着我不能简单地使用此处描述的方法插入此 table:Bulk Insert A Pandas DataFrame Using SQLAlchemy。虽然我有 "Shoes"、"Jacket"、"Bag" 等值。但我需要这些值采用外国 table.
的 ID 形式
我可以使用 xlwings 轻松地将这些数据转换为 DataFrame,但我仍然需要弄清楚如何轻松快速地处理外键转换。
例如Table 1:
product_id country product
1 USA Shoes
2 UK Jacket
3 GER Bag
例如Table 2:
user_id Name
1 John
2 Larry
3 Page
例如Table 3(我要上传的那个):
order_id user product
1 3 2
2 2 2
3 1 1
最后 table 我在 excel:
user bought
John Shoes
Larry Shoes
Page Bag
谢谢!
首先从数据库加载外键,然后映射数据框列。
例如:
engine = create_engine('conn string')
col_tables={'col1':'table1', 'col2':'table2' }
for col, table in col_tables.items()
res = engine.execute("select name, id from {}".format{table})
d = dict(res)
df[col] = df[col].map(d)
有一个包含约 20.000 行数据的工作表,将这些数据插入 postgres 数据库的最佳方法是什么?
我将在其中插入数据的 table 包含许多外键,这意味着我不能简单地使用此处描述的方法插入此 table:Bulk Insert A Pandas DataFrame Using SQLAlchemy。虽然我有 "Shoes"、"Jacket"、"Bag" 等值。但我需要这些值采用外国 table.
的 ID 形式我可以使用 xlwings 轻松地将这些数据转换为 DataFrame,但我仍然需要弄清楚如何轻松快速地处理外键转换。
例如Table 1:
product_id country product
1 USA Shoes
2 UK Jacket
3 GER Bag
例如Table 2:
user_id Name
1 John
2 Larry
3 Page
例如Table 3(我要上传的那个):
order_id user product
1 3 2
2 2 2
3 1 1
最后 table 我在 excel:
user bought
John Shoes
Larry Shoes
Page Bag
谢谢!
首先从数据库加载外键,然后映射数据框列。 例如:
engine = create_engine('conn string')
col_tables={'col1':'table1', 'col2':'table2' }
for col, table in col_tables.items()
res = engine.execute("select name, id from {}".format{table})
d = dict(res)
df[col] = df[col].map(d)