Python处理大文件

来源:互联网 发布:下载蜜蜂软件 编辑:程序博客网 时间:2024/06/05 20:56

1. pickle模块

数据对象持久化。
使用示例:

import pickleimport osimport pandas as pdfile_path="./cache/data.pkl"if os.exists(file_path):    data=pickle.load(open(file_path))#反序列话,把数据解析为一个python对象。存进去是dataframe,解析出来还是dataframeelse:    data=pd.read_csv("./dataset/user_profile.csv")    #中间一系列转换操作    pickle.dump(data,open(file_path)#通过dump把处理好的数据序列化

2.chunk分块读取数据

当一个文件太大,例如几个G,电脑配置限制,无法一次性读入内存,可以分块读入。例如:

import pandas as pdfile_path="./dataset/actions.csv"reader=pd.read_csv(file_path,iterator=True)chunk_size=1000000chunks=[]flag=Truewhile flag:    try:        chunk=reader.get_chunk(chunk_size)        chunks.append(chunk)    except StopIteration:        flag=False        print "Iteration is stopped"df=pd.concat(chunks,ingore_index=True)
0 0
原创粉丝点击