我有一个大文件(2GB)的分类数据(主要是“ Nan”,但随处可见实际值),太大而无法读取到单个数据帧中。我很难找到一个对象来存储每一列的所有唯一值(这是我的目标,最终我需要将其分解为建模对象)
我最终要做的是将文件分块读取到数据帧中,然后获取每一列的唯一值并将它们存储在列表中。我的解决方案可以工作,但似乎大多数不是Python的-在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
因此,master [i]为我提供了列名,然后给出了一个唯一值列表(粗略但确实有效),我主要关心的是,如果可能的话,以“更好”的方式构建列表。
我建议,而不是一个list
的list
S,使用collections.defaultdict(set)
。
说你开始
uniques = collections.defaultdict(set)
现在循环可以变成这样:
for chunk in data:
for col in chunk:
uniques[col] = uniques[col].union(chunk[col].unique())
注意:
defaultdict
总是有一个set
for uniques[col]
(这就是它的作用),因此您可以跳过initialized
和填充。
对于给定的col
,您只需使用当前集合(最初为空,但没有关系)和新的唯一元素的并集来更新条目。
编辑
正如Raymond Hettinger指出的(谢谢!),最好使用
uniques[col].update(chunk[col].unique())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句