我正在玩这款笔记本中的内存压缩示例中的bcolz
到目前为止,我对这个图书馆感到非常惊讶.我认为它是一个伟大的工具,我们所有人都希望将更大的文件加载到小内存(很好的工作Francesc,如果你正在读这个!)
我想知道是否有人有一些加入两个ctable的经验,比如pandas.merge()以及如何做这个时间/内存有效.
感谢您分享您的想法 :-)!
我很快就得到了......非常感谢@mdurant为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))
Run Code Online (Sandbox Code Playgroud)
显然可能有一些更聪明的方法,这个例子不是很具体,但它的工作原理可以作为一个人建立更多的基础
#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
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我创建的版本比pandas慢15倍,但是通过仅使用迭代器,它将节省大量内存.随意评论和/或扩展此.bcolz看起来像是一个伟大的包构建.
| 归档时间: |
|
| 查看次数: |
1381 次 |
| 最近记录: |