python-3.x - 如何将数据从大型数据库加载到 pandas 中?
问题描述
我有一个包含时间序列数据的 postgres 数据库。数据库的大小约为 1 GB。目前要读取数据,这就是我所做的
import psycopg2
import pandas as pd
import pandas.io.sql as psql
conn = psycopg2.connect(database="metrics", user="*******", password="*******", host="localhost", port="5432")
cur = conn.cursor()
df = psql.read_sql("Select * from timeseries", conn)
print(df)
但这会将整个数据加载到内存中。现在我知道可以将数据库转储到 csv 文件的技术,然后可以按照此处的建议分块读取 csv 文件 How to read a 6 GB csv file with pandas
但对我来说,这不是一个选择,因为数据库将不断变化,我需要即时阅读它。是否有任何技术可以分块读取数据库内容或使用任何第三方库?
解决方案
pd.read_sql()也有参数chunksize
,所以你可以从 SQL 表/查询中分块读取数据:
for df in pd.read_sql("Select * from timeseries", conn, chunksize=10**4):
# process `df` chunk here...
推荐阅读
- javascript - 在数组中添加星号?
- regex - 如何在 Sublime 3 中以连续的方式在许多相关文件上自动增加/添加/重新编号?
- android - PC 崩溃后 Android Studio 出现错误
- java - 设置属性“java.io.tmpdir”会导致测试失败
- ruby-on-rails - Rails 脚手架关联 has_many 错误:1 个错误禁止保存此产品
- php - 我的代码有什么问题?我在调用未定义的方法 mysqli::error() 时出错
- php - 尝试使用 ErrorDocument 处理请求时遇到 403 禁止错误。PHP 声音
- html - 为什么这个导航栏不会显示在其他所有内容之上?
- html - Bootstrap 'row' 类不适用于 CDN 或下载版本
- java - 如果我只需要通过套接字发送 1 个字节,我可以只使用一个字符吗?