首页 > 解决方案 > 如何将数据从大型数据库加载到 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

但对我来说,这不是一个选择,因为数据库将不断变化,我需要即时阅读它。是否有任何技术可以分块读取数据库内容或使用任何第三方库?

标签: python-3.xpostgresqlpandasmemory

解决方案


pd.read_sql()也有参数chunksize,所以你可以从 SQL 表/查询中分块读取数据:

for df in pd.read_sql("Select * from timeseries", conn, chunksize=10**4):
    # process `df` chunk here...

推荐阅读