Python bcolz如何合并两个ctables

时间:2014-09-09 10:06:23

标签: python pandas

我正在使用此notebook

中的内存压缩示例中的bcolz

到目前为止,我对这个图书馆感到非常惊讶。我认为它是我们所有人想要将更大的文件加载到小内存中的一个很好的工具(很好的工作Francesc,如果你正在读这个!)

我想知道是否有人有一些加入两个ctable的经验,比如pandas.merge()以及如何有效地执行这段时间。

感谢您分享您的想法: - )!

1 个答案:

答案 0 :(得分:5)

我很及时...非常感谢@mdurant for itertoolz !!这里有一些伪代码,因为我使用的例子是超级丑陋。

# here's generic pandas
df_new = pd.merge(df1,df2) 


# example with itertoolz and bcolz
from toolz.itertoolz import join as joinz
import bcolz

#convert them to ctables
zdf1 = bcolz.ctable.fromdataframe(df1)
zdf2 = bcolz.ctable.fromdataframe(df2)

#column 2 of df1 and column 1 of df2 were the columns to join on
merged = list(joinz(1,zdf1.iter(),0,zdf2.iter()))

# where new_dtypes are the dtypes of the fields you are using
# mine new_dtypes= '|S8,|S8,|S8,|S8,|S8'
zdf3 = bcolz.fromiter(((a[0]+a[1]) for a in merged), dtype = new_dtypes, count = len(merged))

显然可能有一些更聪明的方法,这个例子并不是非常具体,但它有效,可以作为某人建立更多的基础

编辑实例10月21日,美国东部时间晚上7点

#download movielens data files from http://grouplens.org/datasets/movielens/
#I'm using the 1M dataset
import pandas as pd
import time
from toolz.itertoolz import join as joinz
import bcolz

t0 = time()
dset = '/Path/To/Your/Data/'
udata = os.path.join(dset, 'users.dat') 
u_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code']
users = pd.read_csv(udata,sep='::',names=u_cols)

rdata = os.path.join(dset, 'ratings.dat')
r_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']
ratings = pd.read_csv(rdata, sep='::', names=r_cols)

print ("Time for parsing the data: %.2f" % (time()-t0,)) 
#Time for parsing the data: 4.72

t0=time()
users_ratings = pd.merge(users,ratings)
print ("Time for merging the data: %.2f" % (time()-t0,))
#Time for merging the data: 0.14

t0=time()
zratings = bcolz.ctable.fromdataframe(ratings)
zusers = bcolz.ctable.fromdataframe(users)
print ("Time for ctable conversion: %.2f" % (time()-t0,))
#Time for ctable conversion: 0.05

new_dtypes = ','.join([x[0].str for x in zusers.dtype.fields.values()][::-1] +[y[0].str for y in zratings.dtype.fields.values()][::-1])

#Do the merge with a list stored intermediately
t0 = time()
merged = list(joinz(0,zusers.iter(),0,zratings.iter()))
zuser_zrating1 = bcolz.fromiter(((a[0]+a[1]) for a in merged), dtype = new_dtypes, count = len(merged))
print ("Time for intermediate list bcolz merge: %.2f" % (time()-t0,))
#Time for intermediate list bcolz merge: 3.16

# Do the merge ONLY using iterators to limit memory consumption
t0 = time()
zuser_zrating2 = bcolz.fromiter(((a[0]+a[1]) for a in joinz(0,zusers.iter(),0,zratings.iter())) , dtype = new_dtypes, count = sum(1 for _ in joinz(0,zusers.iter(),0,zratings.iter())))
print ("Time for 2x iters of merged bcolz: %.2f" % (time()-t0,))
#Time for 2x iters of merged bcolz: 3.31

正如您所看到的,我创建的版本比pandas慢15倍,但是通过仅使用迭代器,它将节省大量内存。随意评论和/或扩展此。 bcolz看起来像是一个伟大的包装。