pandas SQL块大小 [英] Pandas SQL chunksize

查看:159
本文介绍了 pandas SQL块大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与编程相比,这更多是关于理解的问题. 我对Pandas和SQL很陌生.我正在使用熊猫从具有特定特定块大小的SQL读取数据. 当我运行SQL查询时 将熊猫作为pd导入

This is more of a question on understanding than programming. I am quite new to Pandas and SQL. I am using pandas to read data from SQL with some specific chunksize. When I run a sql query e.g. import pandas as pd

df = pd.read_sql_query('select name, birthdate from table1', chunksize = 1000)

我不明白的是,当我不指定块大小时,数据存储在内存中,但是可以看到内存在增长,但是当我给出块大小时,内存使用率并不高.

What I do not understand is when I do not give a chunksize, data is stored in the memory and I can see the memory growing however, when I give a chunksize the memory usage is not that high.

我知道这个df现在包含许多我可以以

I have is that this df now contains a number of arrays which I can access as

for df_array in df:
    print df.head(5)

我在这里不明白的是,SQL语句的整个结果是否保存在内存中,即df是一个携带多个数组的对象,或者它们就像是指向由SQL查询创建的临时表的指针一样.

What I do not understand here is if the entire result of the SQL statement is kept in memory i.e. df is an object carrying multiple arrays or if these are like pointers pointing towards a temp table created by SQL query.

我很高兴对这个过程的实际运作方式有所了解.

I would be very glad to develop some understanding about how this process is actually working.

推荐答案

让我们考虑两种选择以及两种情况下发生的情况:

Let's consider two options and what happens in both cases:

  1. chunksize为None(默认值):
    • pandas将查询传递到数据库
    • 数据库执行查询
    • pandas检查并发现chunksize为无"
    • pandas告诉数据库它希望立即接收结果表的所有行
    • 数据库返回结果表的所有行
    • pandas将结果表存储在内存中,并将其包装到数据框中
    • 现在您可以使用数据框
  1. chunksize is None(default value):
    • pandas passes query to database
    • database executes query
    • pandas checks and sees that chunksize is None
    • pandas tells database that it wants to receive all rows of the result table at once
    • database returns all rows of the result table
    • pandas stores the result table in memory and wraps it into a data frame
    • now you can use the data frame
  • pandas将查询传递到数据库
  • 数据库执行查询
  • pandas检查并发现chunksize具有一定的价值
  • pandas创建一个查询迭代器(通常为"while True"循环,当数据库提示没有剩余数据时会中断),并在每次需要结果表的下一个块时对其进行迭代
  • pandas告诉数据库它想接收大块大小的行
  • 数据库返回结果表中的下一个chunksize行
  • pandas将下一个chunksize行存储在内存中,并将其包装到数据帧中
  • 现在您可以使用数据框

有关更多详细信息,请参见 pandas \ io \ sql.py 模块,有据可查

For more details you can see pandas\io\sql.py module, it is well documented

这篇关于 pandas SQL块大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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