如何将数据写入 Redshift,这是在 Python 中创建的数据帧的结果? [英] How to write data to Redshift that is a result of a dataframe created in Python?

查看:30
本文介绍了如何将数据写入 Redshift,这是在 Python 中创建的数据帧的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个数据框.我可以将此数据作为新表写入 Redshift 吗?我已成功创建到 Redshift 的数据库连接,并且能够执行简单的 sql 查询.现在我需要给它写一个数据框.

I have a dataframe in Python. Can I write this data to Redshift as a new table? I have successfully created a db connection to Redshift and am able to execute simple sql queries. Now I need to write a dataframe to it.

推荐答案

您可以使用 to_sql 将数据推送到 Redshift 数据库.我已经能够通过 SQLAlchemy 引擎使用与我的数据库的连接来做到这一点.只要确保在您的 to_sql 调用中设置 index = False.如果表不存在,将创建该表,并且您可以指定是否要调用替换表、追加到表中,或者如果表已存在则失败.

You can use to_sql to push data to a Redshift database. I've been able to do this using a connection to my database through a SQLAlchemy engine. Just be sure to set index = False in your to_sql call. The table will be created if it doesn't exist, and you can specify if you want you call to replace the table, append to the table, or fail if the table already exists.

from sqlalchemy import create_engine
import pandas as pd

conn = create_engine('postgresql://username:password@yoururl.com:5439/yourdatabase')

df = pd.DataFrame([{'A': 'foo', 'B': 'green', 'C': 11},{'A':'bar', 'B':'blue', 'C': 20}])

df.to_sql('your_table', conn, index=False, if_exists='replace')

请注意,您可能需要 pip install psycopg2 以便通过 SQLAlchemy 连接到 Redshift.

Note that you may need to pip install psycopg2 in order to connect to Redshift through SQLAlchemy.

to_sql 文档

这篇关于如何将数据写入 Redshift,这是在 Python 中创建的数据帧的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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