【问题标题】:Transforming a Pandas DataFrame into a VALUES sql statement将 Pandas DataFrame 转换为 VALUES sql 语句
【发布时间】:2019-06-03 15:46:01
【问题描述】:

在 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,但绑定参数似乎只适用于有限数量的参数,理想情况下,我希望以 C 速度将数据帧序列化为文本。

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

【问题讨论】:

  • 我有一个类似的,我保存为 proc 并使用 pandas i pd.read_sql_query('EXEC proc_name')。如果我误解了查询,请告诉我

标签: python pandas postgresql sqlalchemy


【解决方案1】:

您可以使用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

【讨论】:

  • 这可能是一个不错的解决方法,但它会很烦人,因为我正在一个 sqlalchemy 事务中工作,我正在执行常规(但不相关的)orm 操作。
  • 我添加了一些代码来展示如何使用psycopg2 在不执行的情况下生成 SQL。然后你可以使用 sqlalchemy 来执行 SQL。
  • 谢谢。我也看了一点,似乎我可以通过 session.connection.connection 访问我当前的事务连接。如果是这样的话,这基本上可以解决我的问题。我会让它再打开几个小时,看看是否会出现更纯粹的 pandas/sqlalchemy 响应,但您的解决方案似乎适合。
猜你喜欢
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 2017-03-23
  • 2011-10-18
  • 1970-01-01
  • 2013-02-15
  • 2019-07-03
相关资源
最近更新 更多