gpt4 book ai didi

python - 将 Pandas DataFrame 转换为 VALUES sql 语句

转载 作者:行者123 更新时间:2023-11-29 12:50:03 25 4
gpt4 key购买 nike

在 python 中使用 pandas,我需要能够生成从数据帧到 postgresql 的高效查询。不幸的是,DataFrame.to_sql(...) 仅执行直接插入,而我希望进行的查询相当复杂。

理想情况下,我想这样做:

WITH my_data AS (
SELECT * FROM (
VALUES
<dataframe data>
) AS data (col1, col2, col3)
)
UPDATE my_table
SET
my_table.col1 = my_data.col1,
my_table.col2 = complex_function(my_table.col2, my_data.col2),
FROM my_data
WHERE my_table.col3 < my_data.col3;

但是,要做到这一点,我需要将我的数据框变成一个简单的值声明。当然,我可以重写自己的函数,但过去的经验告诉我,永远不应该手动编写函数来转义和清理 sql。

我们正在使用 SQLAlchemy,但绑定(bind)参数似乎只适用于有限数量的参数,理想情况下,我希望以 C 速度将数据帧序列化为文本。

那么,有没有办法通过 pandas 或 SQLAlchemy 将我的数据框有效地转换为值子语句,并将其插入到我的查询中?

最佳答案

你可以使用 psycopg2.extras.execute_values .例如,给定此设置

CREATE TABLE my_table (
col1 int
, col2 text
, col3 int
);
INSERT INTO my_table VALUES
(99, 'X', 1)
, (99, 'Y', 2)
, (99, 'Z', 99);

# | col1 | col2 | col3 |
# |------+------+------|
# | 99 | X | 1 |
# | 99 | Y | 2 |
# | 99 | Z | 99 |

python代码

import psycopg2
import psycopg2.extras as pge
import pandas as pd
import config

df = pd.DataFrame([
(1, 'A', 10),
(2, 'B', 20),
(3, 'C', 30)])

with psycopg2.connect(host=config.HOST, user=config.USER, password=config.PASS, database=config.USER) as conn:
with conn.cursor() as cursor:
sql = '''WITH my_data AS (
SELECT * FROM (
VALUES %s
) AS data (col1, col2, col3)
)
UPDATE my_table
SET
col1 = my_data.col1,
-- col2 = complex_function(col2, my_data.col2)
col2 = my_table.col2 || my_data.col2
FROM my_data
WHERE my_table.col3 < my_data.col3'''

pge.execute_values(cursor, sql, df.values)

my_table 更新为

# SELECT * FROM my_table
| col1 | col2 | col3 |
|------+------+------|
| 99 | Z | 99 |
| 1 | XA | 1 |
| 1 | YA | 2 |

或者,您可以使用 psycopg2生成 SQL。format_values 中的代码几乎完全是从 source code for pge.execute_values 复制而来的.

import psycopg2
import psycopg2.extras as pge
import pandas as pd
import config

df = pd.DataFrame([
(1, "A'foo'", 10),
(2, 'B', 20),
(3, 'C', 30)])


def format_values(cur, sql, argslist, template=None, page_size=100):
enc = pge._ext.encodings[cur.connection.encoding]
if not isinstance(sql, bytes):
sql = sql.encode(enc)
pre, post = pge._split_sql(sql)
result = []
for page in pge._paginate(argslist, page_size=page_size):
if template is None:
template = b'(' + b','.join([b'%s'] * len(page[0])) + b')'
parts = pre[:]
for args in page:
parts.append(cur.mogrify(template, args))
parts.append(b',')
parts[-1:] = post
result.append(b''.join(parts))
return b''.join(result).decode(enc)

with psycopg2.connect(host=config.HOST, user=config.USER, password=config.PASS, database=config.USER) as conn:
with conn.cursor() as cursor:
sql = '''WITH my_data AS (
SELECT * FROM (
VALUES %s
) AS data (col1, col2, col3)
)
UPDATE my_table
SET
col1 = my_data.col1,
-- col2 = complex_function(col2, my_data.col2)
col2 = my_table.col2 || my_data.col2
FROM my_data
WHERE my_table.col3 < my_data.col3'''

print(format_values(cursor, sql, df.values))

产量

WITH my_data AS (
SELECT * FROM (
VALUES (1,'A''foo''',10),(2,'B',20),(3,'C',30)
) AS data (col1, col2, col3)
)
UPDATE my_table
SET
col1 = my_data.col1,
-- col2 = complex_function(col2, my_data.col2)
col2 = my_table.col2 || my_data.col2
FROM my_data
WHERE my_table.col3 < my_data.col3

关于python - 将 Pandas DataFrame 转换为 VALUES sql 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56430626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com