使用pypyodbc和pandas加载1GB .accdb时出现内存错误

时间:2016-07-04 21:52:17

标签: python pandas ms-access pypyodbc

我正在尝试做一些可能不可能或可能以不同方式完成的事情......

我必须读取1 GB的Access文件并在pandas中操作它;由于cursor.fetchall()直接与Memory Error失败,我尝试使用下面的函数来查看内存错误发生的时间:它出现在400.000行之后(总数为1.12 Mrows)。

很奇怪,因为我的机器里有8 GB的ram,它似乎是免费的50%。我还将虚拟内存设置为16 GB,但结果没有改变。

我不需要微积分速度,所以任何肮脏的解决方案都是受欢迎的:)包括使用硬盘作为ram(我有一个ssd)。

有一种方法可以让所有内存都可用于python吗?

已经失败的方法:

  • 单行抓取:cursor.fetchone()
  • 许多行抓取:cursor.fetchmany()
  • 所有行抓取:cursor.fetchall()
  • pandas read_sql传递chunksizepandas.read_sql(query, conn, chunksize=chunksize)(thx为用户MaxU)

功能:

def msaccess_to_df (abs_path, query):
    conn = pypyodbc.connect(
        r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
        r"Dbq=" + abs_path + ";" )

    cur = conn.cursor()
    cur.execute( query )

    fields = zip(*cur.description)[0]
    df = pandas.DataFrame(columns=fields)

    fetch_lines_per_block = 5000
    i = 0
    while True:
        rows = cur.fetchmany(fetch_lines_per_block) # <-----
        if len(rows) == 0: break
        else:
            rd = [dict(zip(fields, r)) for r in rows]
            df = df.append(rd, ignore_index=True)
            del rows
            del rd
        i+=1
        print 'fetched', i*fetch_lines_per_block, 'lines'

    cur.close()
    conn.close()

    return df

错误:

df = df.append(rd, ignore_index=True)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 4338, in append
    verify_integrity=verify_integrity)
  File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 845, in concat
    copy=copy)
  File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 904, in __init__
    obj.consolidate(inplace=True)
  File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 2747, in consolidate
    self._consolidate_inplace()
  File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 2729, in _consolidate_inplace
    self._protect_consolidate(f)
  File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 2718, in _protect_consolidate
    result = f()
  File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 2727, in f
    self._data = self._data.consolidate()
  File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3273, in consolidate
    bm._consolidate_inplace()
  File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3278, in _consolidate_inplace
    self.blocks = tuple(_consolidate(self.blocks))
  File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 4269, in _consolidate
    _can_consolidate=_can_consolidate)
  File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 4292, in _merge_blocks
    new_values = new_values[argsort]
MemoryError

####################编辑 - 已解决##################### /强>

最后我用

解决了

这样任何方法都可以。

1 个答案:

答案 0 :(得分:1)

我会使用原生pandas方法 - read_sql()而不是在循环中手动获取行:

def msaccess_to_df (abs_path, query):
    conn = pypyodbc.connect(
        r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
        r"Dbq=" + abs_path + ";" )

    df = pd.read_sql(query, conn)
    conn.close()
    return df

如果您仍然收到MemoryError例外,请尝试以块的形式读取您的数据:

def msaccess_to_df (abs_path, query, chunksize=10**5):
    conn = pypyodbc.connect(
        r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
        r"Dbq=" + abs_path + ";" )

    df = pd.concat([x for x in pd.read_sql(query, conn, chunksize=chunksize)],
                   ignore_index=True)
    conn.close()
    return df

PS这应该给你一个想法,但请注意我没有测试这段代码,所以它可能需要一些调试......