使用Pandas在MySQL中创建临时表

Mon*_*eck 8 python mysql temp-tables pandas

Pandas有一个很棒的功能,您可以在其中将数据帧写入SQL中的表.

df.to_sql(con=cnx, name='some_table_name', if_exists='replace', flavor='mysql', index=False)

有没有办法以这种方式制作临时表?

据我所知,文档中没有任何内容.

ale*_*cxe 12

DataFrame.to_sql()使用内置到大熊猫pandas.io.sql,其本身依赖于SQLAlchemy的作为数据库抽象层.要在SQLAlchemy ORM中创建"临时"表,您需要提供前缀:

t = Table(
    't', metadata,
    Column('id', Integer, primary_key=True),
    # ...
    prefixes=['TEMPORARY'],
)
Run Code Online (Sandbox Code Playgroud)

从我看到的,pandas.io.sql 不允许您指定prefixes或轻松更改表的创建方式.

解决这个问题的一个办法是事先创建临时表,并使用to_sql()if_exists="append"(都使用相同的数据库连接).


这也是我试图做的:覆盖pandas.io.sql.SQLTable's _create_table_setup()方法并传递prefixesTable构造函数.出于某种原因,该表仍然是非临时的.不确定它是否会有所帮助,但这里是我使用的代码:gist.这有点像hacky,但我希望它至少可以作为一个示例代码来帮助您开始这种方法.


iam*_*mbo 7

简单的解决方法,无需花哨的魔法

这对我来说是一个快速而简单的解决方法。

只需将正则表达式应用于生成的 SQL,即可添加您想要的任何语句。

import io
import pandas as pd

# Get the SQL that would be generated by the create table statement
create_table_sql = pd.io.sql.get_schema(df, tmp_table_name)

# Replace the `CREATE TABLE` part of the generated statement with 
# whatever you need.
create_tmp_table_sql = re.sub(
    "^(CREATE TABLE)?",
    "CREATE TEMP TABLE",
    create_table_sql
)
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样使用它:

# Write to the database in a transaction (psycopg2)
with conn.cursor() as cur:
    cur.execute(create_tmp_table_sql)
    output = io.StringIO()
    df.to_csv(output, sep="\t", header=False, index=False, na_rep="NULL")
    output.seek(0)
    cur.copy_from(output, tmp_table_name, null="NULL")
Run Code Online (Sandbox Code Playgroud)

感谢Aseem提供了一种快速写入 Postgres 的方法。