大熊猫中持久的DataFrame

我正在探索作为长期SAS用户切换到python和pandas。

但是,今天在运行一些测试时,我感到惊讶的是,python在试图pandas.read_csv()一个128mb的csv文件时耗尽了内存。 它有大约20万行和200列的大部分数字数据。

借助SAS,我可以将csv文件导入SAS数据集,并且可以与我的硬盘一样大。

pandas有类似的东西吗?

我经常使用大文件,无法访问分布式计算网络。


原则上,它不应该耗尽内存,但目前由于一些复杂的Python内部问题导致的read_csv对大文件存在内存问题(这很模糊,但它很久以前就已知了:http://github.com/ pydata /熊猫/问题/ 407)。

目前还没有一个完美的解决方案(这是一个单调乏味的解决方案:你可以将文件逐行地转录成预分配的NumPy数组或内存映射文件np.mmap ),但这是一个'我会在不久的将来工作。 另一种解决方案是以较小的块读取文件(使用iterator=True, chunksize=1000 ),然后与pd.concat连接。 当你将整个文本文件拖入内存时,问题就出现了。


韦斯当然是对的! 我只是想提供一些更完整的示例代码。 我对129 Mb文件有同样的问题,解决方法是:

from pandas import *

tp = read_csv('large_dataset.csv', iterator=True, chunksize=1000)  # gives TextFileReader, which is iterable with chunks of 1000 rows.
df = concat(tp, ignore_index=True)  # df is DataFrame. If errors, do `list(tp)` instead of `tp`

这是一个较旧的线程,但我只想在此处转储我的解决方法解决方案。 我最初尝试了chunksize参数(即使像10000这样的非常小的值),但它没有多大帮助; 内存大小仍然存在技术问题(我的CSV是〜7.5 Gb)。

现在,我只是在for-loop方法中读取了大量的CSV文件,并将它们例如逐步添加到SQLite数据库中:

import pandas as pd
import sqlite3
from pandas.io import sql
import subprocess

# In and output file paths
in_csv = '../data/my_large.csv'
out_sqlite = '../data/my.sqlite'

table_name = 'my_table' # name for the SQLite database table
chunksize = 100000 # number of lines to process at each iteration

# columns that should be read from the CSV file
columns = ['molecule_id','charge','db','drugsnow','hba','hbd','loc','nrb','smiles']

# Get number of lines in the CSV file
nlines = subprocess.check_output('wc -l %s' % in_csv, shell=True)
nlines = int(nlines.split()[0]) 

# connect to database
cnx = sqlite3.connect(out_sqlite)

# Iteratively read CSV and dump lines into the SQLite table
for i in range(0, nlines, chunksize):

    df = pd.read_csv(in_csv,  
            header=None,  # no header, define column header manually later
            nrows=chunksize, # number of rows to read at each iteration
            skiprows=i)   # skip rows that were already read

    # columns to read        
    df.columns = columns

    sql.to_sql(df, 
                name=table_name, 
                con=cnx, 
                index=False, # don't use CSV file index
                index_label='molecule_id', # use a unique column from DataFrame as index
                if_exists='append') 
cnx.close()    
链接地址: http://www.djcxy.com/p/53533.html

上一篇: Large, persistent DataFrame in pandas

下一篇: Renaming columns in pandas