【问题标题】:Retrieve Large Data From MySQL DB With Chunks And Save Them Dataframe Pandas使用块从 MySQL 数据库中检索大数据并保存它们 Dataframe Pandas
【发布时间】:2020-08-02 00:55:56
【问题描述】:

我想从 SQL 数据库中检索大约 1 亿行和 30 列数据到一个数据框中,我可以在其中根据某些要求进行排序和过滤。我只有 2 Gig 内存。即使我使用的是 chunksize,一切都会停止。这是我的代码。

import pymysql
chunksize = 100
import pandas as pd
import pymysql.cursors
from urllib import parse```

sqlEngine = create_engine('mysql+pymysql://username:%s@localhost/db' % parse.unquote_plus('password'))
dbConnection    = sqlEngine.connect()

for chunk in pd.read_sql("select * from db.db_table", dbConnection, chunksize = chunksize):
    print(chunk)

Do somrthing with chunk(chunk is the dataframe that has all the 100 million columns )

我已经减少了我的块大小,但仍然没有得到任何东西。

【问题讨论】:

  • 使用像select * from db.db_table 这样的查询,数据库仍然必须开始检索所有 3000 万行。选择一个您可以排序的索引列,按它排序并添加合适的LIMIT ... OFFSET ... 开头
  • 我需要全部数据进行数据分析。
  • 什么分析?您可能可以在 SQL 中做很多事情,而不是尝试将内容加载到 Pandas 中。

标签: python mysql pandas large-data


【解决方案1】:

详细说明我的评论,类似这样。

不过,我预计您将很难在 2 GB 的内存中容纳 1 亿行 x 30 列。

df = None
for offset in itertools.count(step=chunksize):
    print("Reading chunk %d..." % offset)
    query = "select * from db.db_table order by id limit %d offset %d" % (chunksize, offset)
    chunk_df = pd.read_sql(query, dbConnection)
    if not chunk_df:  # TODO: this check might not be correct
        # No data in new chunk, so we probably have it all
        break
    if not df:
        df = chunk_df
    else:
        df = pd.concat([df, chunk_df], copy=False)

# do things with DF

【讨论】:

  • 这仍然是问题,但会找到解决方法,谢谢您的帮助?
猜你喜欢
  • 2021-12-13
  • 2021-07-10
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多