使用to_sql将数据附加到pandas中已经存在的表中 [英] append the data to already existing table in pandas using to_sql

查看:842
本文介绍了使用to_sql将数据附加到pandas中已经存在的表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框

ipdb> csv_data
  country    sale        date  trans_factor
0   India  403171  12/01/2012             1
1  Bhutan  394096  12/01/2012             2
2   Nepal   super  12/01/2012             3
3  madhya  355883  12/01/2012             4
4   sudan     man  12/01/2012             5

到目前为止,我正在使用下面的代码在表中插入数据,例如如果表已经存在,则将其删除并创建新表

As of now i am using below code to insert data in table, like if table already exists, drop it and create new table

csv_file_path = data_mapping_record.csv_file_path
original_csv_header = pandas.read_csv(csv_file_path).columns.tolist()
csv_data = pandas.read_csv(csv_file_path, skiprows=[0], names=original_csv_header, infer_datetime_format=True)
table_name = data_mapping_record.csv_file_path.split('/')[-1].split('.')[0]
engine = create_engine(
    'postgresql://username:password@localhost:5432/pandas_data')

# Delete table if already exits
engine.execute("""DROP TABLE IF EXISTS "%s" """ % (table_name))

# Write the pandas dataframe to database using sqlalchemy and pands.to_sql
csv_data_frame.to_sql(table_name, engine, chunksize=1000)

但是我需要的是不删除表,如果表已经存在,只需将数据追加到已经存在的表中,熊猫to_sql方法中有什么办法吗?

But what i need is, without deleting the table, if table already exists just append the data to the already existing one, is there any way in pandas to_sql method ?

推荐答案

IIUC,您可以简单地使用

IIUC you can simply use if_exists='append' parameter:

csv_data_frame.to_sql(table_name, engine, if_exists='append', chunksize=1000)

来自文档:

if_exists :{失败",替换",添加"},默认为失败"

if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’

失败:如果 表存在,什么也不做.

fail: If table exists, do nothing.

替换:如果表存在,则将其删除,然后重新创建 并插入数据.

replace: If table exists, drop it, recreate it, and insert data.

追加:如果表存在,则插入数据.创建是否 不存在.

append: If table exists, insert data. Create if does not exist.

这篇关于使用to_sql将数据附加到pandas中已经存在的表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆