首页 > 解决方案 > 即使在块加载时,从 postgresql 获取数据也会占用大量内存

问题描述

我有一个大约 600000 行和 100 列的 postgreSQL DB,它需要大约 500 MB RAM。我现在尝试通过加载它

con = pyodbc.connect("DSN="+DSN)
df = pd.read_sql(query ,con)

由于内存错误,最终导致 9+ GB 的 RAM 使用和崩溃。

我现在尝试了几种解决方法:

“手动”使用获取行fetchmany

eng = create_engine(f'postgresql://{self.user}:{self.pwd}@{self.host}:{self.port}/{self.db}',server_side_cursors=True)
#or 
#eng = create_engine(f'postgresql://{self.user}:{self.pwd}@{self.host}:{self.port}/{self.db}',execution_options={"stream_results":True})
con = eng.connect()
ex = con.execute(query)
           
def __fetch_iter__(self,ex,chunksize):
        """
        Generator for loading in chunks
        """
        fetch = True
        while fetch:
           fetch = ex.fetchmany(chunksize)
           
           yield pd.DataFrame(fetch)

df = pd.concat(__fetch_iter__(ex,chunksize))

根据这个,确实应该每次只加载给定数量的行。

即使chunksize=10我的内存超过 6GB

标签: pythonpandaspostgresqlpsycopg2

解决方案


推荐阅读