python - 即使在块加载时,从 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
解决方案
推荐阅读
- flutter - 如何在不重新渲染整个屏幕的情况下在屏幕上加载更多数据?
- php - Wordpress 获取帖子类型,仅限自定义帖子类型
- c# - Autofac注册通用存储库,其中T不是类
- mysql - Laravel Eloquent:如果行不存在则返回一些值
- android - Android 电视运营商层
- scala - 这个 .get(x) 行为从何而来?
- javascript - 正则表达式删除与表达式不匹配的字符
- php - 用于模拟数组左连接的函数在 PHP 中无法正常工作
- linux - 我有一些代码,其中有一个命令在终端上运行良好,但在从脚本运行时失败
- c# - 使用 RestSharp XmlSerializer 将 List 属性序列化为父级的内容