我正在探索切换到Python和大熊猫作为一个长期的SAS用户。
然而,今天运行一些测试的时候,我感到惊讶的是蟒蛇试图当用完了内存pandas.read_csv()
128MB的CSV文件。 它有大约200,000行和大部分数字数据的200列。
随着SAS,我可以导入CSV文件导入SAS数据集,它可以为我的硬盘一样大。
有什么类似的pandas
?
我经常使用大文件,并没有访问分布式计算网络。
我正在探索切换到Python和大熊猫作为一个长期的SAS用户。
然而,今天运行一些测试的时候,我感到惊讶的是蟒蛇试图当用完了内存pandas.read_csv()
128MB的CSV文件。 它有大约200,000行和大部分数字数据的200列。
随着SAS,我可以导入CSV文件导入SAS数据集,它可以为我的硬盘一样大。
有什么类似的pandas
?
我经常使用大文件,并没有访问分布式计算网络。
原则上,不应该耗尽内存,但目前有记忆问题read_csv
上造成了一些复杂的Python内部问题大文件(这是模糊的,但它已经认识了很长一段时间: http://github.com/ pydata /熊猫/问题/ 407 )。
目前还没有一个完美的解决方案(这里是一个繁琐的一个:你可以在文件一行一行地抄写成预分配NumPy的阵列或存储器映射file-- 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)。
现在,我刚才读的CSV文件的数据块在for循环的方法,并将它们添加例如,要一步一个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()
下面是我的工作流程。
import sqlalchemy as sa
import pandas as pd
import psycopg2
count = 0
con = sa.create_engine('postgresql://postgres:pwd@localhost:00001/r')
#con = sa.create_engine('sqlite:///XXXXX.db') SQLite
chunks = pd.read_csv('..file', chunksize=10000, encoding="ISO-8859-1",
sep=',', error_bad_lines=False, index_col=False, dtype='unicode')
底座上的文件大小,你最好优化CHUNKSIZE。
for chunk in chunks:
chunk.to_sql(name='Table', if_exists='append', con=con)
count += 1
print(count)
在数据库的所有数据后,就可以查询出那些你从数据库所需要的。
如果要加载巨大的CSV文件,DASK可能是一个不错的选择。 它模仿大熊猫的API,所以感觉非常相似,熊猫
链接到GitHub上DASK
您可以使用Pytable而不是熊猫DF。 它是专为大型数据集,文件格式为HDF5。 因此,处理时间也比较快。