我有一个大的文件(2GB)的分类数据(主要是“南” - 但实际值在这里和那里填充),这是太大,无法读入一个单一的数据帧。我有一个相当困难的时候想出一个对象来存储每列的所有唯一值(这是我的目标 - 最终我需要将这个因子分解为建模)Pythonic的方式来增长列表
我最终做的是读取文件以块形式存储到数据框中,然后获取每列的唯一值并将它们存储在列表中。我的解决方案很有效,但看起来最没有pythonic - 是否有更简洁的方式在Python中实现这一点(3.5版本)。我知道列数(〜2100)。
import pandas as pd
#large file of csv separated text data
data=pd.read_csv("./myratherlargefile.csv",chunksize=100000, dtype=str)
collist=[]
master=[]
i=0
initialize=0
for chunk in data:
#so the first time through I have to make the "master" list
if initialize==0:
for col in chunk:
#thinking about this, i should have just dropped this col
if col=='Id':
continue
else:
#use pd.unique as a build in solution to get unique values
collist=chunk[col][chunk[col].notnull()].unique().tolist()
master.append(collist)
i=i+1
#but after first loop just append to the master-list at
#each master-list element
if initialize==1:
for col in chunk:
if col=='Id':
continue
else:
collist=chunk[col][chunk[col].notnull()].unique().tolist()
for item in collist:
master[i]=master[i]+collist
i=i+1
initialize=1
i=0
在那之后,我对所有的独特的价值观最终任务如下:
i=0
names=chunk.columns.tolist()
for item in master:
master[i]=list(set(item))
master[i]=master[i].append(names[i+1])
i=i+1
从而掌握[I]给我的列名,然后唯一值的列表 - 原油,但它确实有用 - 我主要关心的是如果可能的话,以“更好”的方式建立清单。
您曾经考虑过使用一台发电机懒洋洋地读取文件? (查找yield关键字) – salparadise
这可能会诀窍。我对迭代器和生成器不太了解 - 但按照建议粗略浏览一下yield关键字似乎是正确的。 – RDS
这实际上是在引擎盖下使用发电机。大块大小就是这样做的。出于好奇,你在32位或64位机器上运行/ python? 'import sys;打印(sys.maxsize)'应该工作,只要你正在运行python 2.6 –