美文网首页
Python 处理大文件并用pickle保存

Python 处理大文件并用pickle保存

作者: minningl | 来源:发表于2017-11-15 14:34 被阅读963次

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

import pandas as pd
file_path="./dataset/actions.csv"
reader=pd.read_csv(file_path,iterator=True)
chunk_size=1000000
chunks=[]
flag=True
while 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)

2、读取之后使用pickle 模块进行持久化

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

相关文章

网友评论

      本文标题:Python 处理大文件并用pickle保存

      本文链接:https://www.haomeiwen.com/subject/dkocvxtx.html