免责声明:这个答案是实验性的,而不是实用的,但也许值得一提。
我发现该类
pandas.io.sql.SQLTable已命名为参数
key,如果您为其分配了字段名称,则该字段将成为主键:
不幸的是,您不能只从
Dataframe.to_sql()函数传递此参数。要使用它,您应该:
创建
pandas.io.SQLDatabase
实例engine = sa.create_engine('postgresql:///somedb')pandas_sql = pd.io.sql.pandasSQL_builder(engine, schema=None, flavor=None)
定义函数类似于
pandas.io.SQLDatabase.to_sql()
但带有附加*kwargs
参数的函数,该函数传递给pandas.io.SQLTable
在内部创建的对象(我刚刚复制了原始to_sql()
方法并添加了*kwargs
):def to_sql_k(self, frame, name, if_exists='fail', index=True, index_label=None, schema=None, chunksize=None, dtype=None, **kwargs):if dtype is not None: from sqlalchemy.types import to_instance, TypeEngine for col, my_type in dtype.items(): if not isinstance(to_instance(my_type), TypeEngine): raise ValueError('The type of %s is not a SQLAlchemy ' 'type ' % col)table = pd.io.sql.SQLTable(name, self, frame=frame, index=index, if_exists=if_exists, index_label=index_label, schema=schema, dtype=dtype, **kwargs)table.create()table.insert(chunksize)使用
SQLDatabase
实例和要保存的数据框调用此函数to_sql_k(pandas_sql, df2save, 'tmp', index=True, index_label='id', keys='id', if_exists='replace')
我们得到类似
CREATE TABLE public.tmp( id bigint NOT NULL DEFAULT nextval('tmp_id_seq'::regclass),...)在数据库中。
PS当然,您可以安装monkey-patch
Dataframe,
io.SQLDatabase并
io.to_sql()可以方便地使用此替代方法。



