Python利用多进程将大量数据放入有限内存的教程


Posted in Python onApril 01, 2015

简介

这是一篇有关如何将大量的数据放入有限的内存中的简略教程。

与客户工作时,有时会发现他们的数据库实际上只是一个csv或Excel文件仓库,你只能将就着用,经常需要在不更新他们的数据仓库的情况下完成工作。大部分情况下,如果将这些文件存储在一个简单的数据库框架中或许更好,但时间可能不允许。这种方法对时间、机器硬件和所处环境都有要求。

下面介绍一个很好的例子:假设有一堆表格(没有使用Neo4j、MongoDB或其他类型的数据库,仅仅使用csvs、tsvs等格式存储的表格),如果将所有表格组合在一起,得到的数据帧太大,无法放入内存。所以第一个想法是:将其拆分成不同的部分,逐个存储。这个方案看起来不错,但处理起来很慢。除非我们使用多核处理器。
目标

这里的目标是从所有职位中(大约1万个),找出相关的的职位。将这些职位与政府给的职位代码组合起来。接着将组合的结果与对应的州(行政单位)信息组合起来。然后用通过word2vec生成的属性信息在我们的客户的管道中增强已有的属性。

这个任务要求在短时间内完成,谁也不愿意等待。想象一下,这就像在不使用标准的关系型数据库的情况下进行多个表的连接。
数据

Python利用多进程将大量数据放入有限内存的教程

示例脚本

下面的是一个示例脚本,展示了如何使用multiprocessing来在有限的内存空间中加速操作过程。脚本的第一部分是和特定任务相关的,可以自由跳过。请着重关注第二部分,这里侧重的是multiprocessing引擎。

#import the necessary packages
import pandas as pd
import us
import numpy as np
from multiprocessing import Pool,cpu_count,Queue,Manager
 
# the data in one particular column was number in the form that horrible excel version
# of a number where '12000' is '12,000' with that beautiful useless comma in there.
# did I mention I excel bothers me?
# instead of converting the number right away, we only convert them when we need to
def median_maker(column):
  return np.median([int(x.replace(',','')) for x in column])
 
# dictionary_of_dataframes contains a dataframe with information for each title; e.g title is 'Data Scientist'
# related_title_score_df is the dataframe of information for the title; columns = ['title','score']
### where title is a similar_title and score is how closely the two are related, e.g. 'Data Analyst', 0.871
# code_title_df contains columns ['code','title']
# oes_data_df is a HUGE dataframe with all of the Bureau of Labor Statistics(BLS) data for a given time period (YAY FREE DATA, BOO BAD CENSUS DATA!)
 
def job_title_location_matcher(title,location):
  try:
    related_title_score_df = dictionary_of_dataframes[title]
    # we limit dataframe1 to only those related_titles that are above
    # a previously established threshold
    related_title_score_df = related_title_score_df[title_score_df['score']>80]
 
    #we merge the related titles with another table and its codes
    codes_relTitles_scores = pd.merge(code_title_df,related_title_score_df)
    codes_relTitles_scores = codes_relTitles_scores.drop_duplicates()
 
    # merge the two dataframes by the codes
    merged_df = pd.merge(codes_relTitles_scores, oes_data_df)
    #limit the BLS data to the state we want
    all_merged = merged_df[merged_df['area_title']==str(us.states.lookup(location).name)]
 
    #calculate some summary statistics for the time we want
    group_med_emp,group_mean,group_pct10,group_pct25,group_median,group_pct75,group_pct90 = all_merged[['tot_emp','a_mean','a_pct10','a_pct25','a_median','a_pct75','a_pct90']].apply(median_maker)
    row = [title,location,group_med_emp,group_mean,group_pct10,group_pct25, group_median, group_pct75, group_pct90]
    #convert it all to strings so we can combine them all when writing to file
    row_string = [str(x) for x in row]
    return row_string
  except:
    # if it doesnt work for a particular title/state just throw it out, there are enough to make this insignificant
    'do nothing'

这里发生了神奇的事情:

#runs the function and puts the answers in the queue
def worker(row, q):
    ans = job_title_location_matcher(row[0],row[1])
    q.put(ans)
 
# this writes to the file while there are still things that could be in the queue
# this allows for multiple processes to write to the same file without blocking eachother
def listener(q):
  f = open(filename,'wb')
  while 1:
    m = q.get()
    if m =='kill':
        break
    f.write(','.join(m) + 'n')
    f.flush()
  f.close()
 
def main():
  #load all your data, then throw out all unnecessary tables/columns
  filename = 'skill_TEST_POOL.txt'
 
  #sets up the necessary multiprocessing tasks
  manager = Manager()
  q = manager.Queue()
  pool = Pool(cpu_count() + 2)
  watcher = pool.map_async(listener,(q,))
 
  jobs = []
  #titles_states is a dataframe of millions of job titles and states they were found in
  for i in titles_states.iloc:
    job = pool.map_async(worker, (i, q))
    jobs.append(job)
 
  for job in jobs:
    job.get()
  q.put('kill')
  pool.close()
  pool.join()
 
if __name__ == "__main__":
  main()

由于每个数据帧的大小都不同(总共约有100Gb),所以将所有数据都放入内存是不可能的。通过将最终的数据帧逐行写入内存,但从来不在内存中存储完整的数据帧。我们可以完成所有的计算和组合任务。这里的“标准方法”是,我们可以仅仅在“job_title_location_matcher”的末尾编写一个“write_line”方法,但这样每次只会处理一个实例。根据我们需要处理的职位/州的数量,这大概需要2天的时间。而通过multiprocessing,只需2个小时。

虽然读者可能接触不到本教程处理的任务环境,但通过multiprocessing,可以突破许多计算机硬件的限制。本例的工作环境是c3.8xl ubuntu ec2,硬件为32核60Gb内存(虽然这个内存很大,但还是无法一次性放入所有数据)。这里的关键之处是我们在60Gb的内存的机器上有效的处理了约100Gb的数据,同时速度提升了约25倍。通过multiprocessing在多核机器上自动处理大规模的进程,可以有效提高机器的利用率。也许有些读者已经知道了这个方法,但对于其他人,可以通过multiprocessing能带来非常大的收益。顺便说一句,这部分是skill assets in the job-market这篇博文的延续。

Python 相关文章推荐
详解Python中映射类型的内建函数和工厂函数
Aug 19 Python
Python面向对象程序设计之继承与多继承用法分析
Jul 13 Python
Python从使用线程到使用async/await的深入讲解
Sep 16 Python
Python正则匹配判断手机号是否合法的方法
Dec 09 Python
NumPy 基本切片和索引的具体使用方法
Apr 24 Python
python3爬虫学习之数据存储txt的案例详解
Apr 24 Python
python调用动态链接库的基本过程详解
Jun 19 Python
Python基于机器学习方法实现的电影推荐系统实例详解
Jun 25 Python
利用Tensorflow构建和训练自己的CNN来做简单的验证码识别方式
Jan 20 Python
Python浮点型(float)运算结果不正确的解决方案
Sep 22 Python
python 两种方法修改文件的创建时间、修改时间、访问时间
Sep 26 Python
Pandas加速代码之避免使用for循环
May 30 Python
python连接远程ftp服务器并列出目录下文件的方法
Apr 01 #Python
10种检测Python程序运行时间、CPU和内存占用的方法
Apr 01 #Python
深入Python解释器理解Python中的字节码
Apr 01 #Python
Python中的defaultdict模块和namedtuple模块的简单入门指南
Apr 01 #Python
Python进行数据科学工作的简单入门教程
Apr 01 #Python
10个易被忽视但应掌握的Python基本用法
Apr 01 #Python
用Python制作检测Linux运行信息的工具的教程
Apr 01 #Python
You might like
一个oracle+PHP的查询的例子
2006/10/09 PHP
一个PHP操作Access类(PHP+ODBC+Access)
2007/01/02 PHP
php替换字符串中间字符为省略号的方法
2015/05/04 PHP
CI框架(ajax分页,全选,反选,不选,批量删除)完整代码详解
2016/11/01 PHP
php中static 静态变量和普通变量的区别
2016/12/01 PHP
tp5(thinkPHP5)框架连接数据库的方法示例
2018/12/24 PHP
基于JavaScript实现继承机制之原型链(prototype chaining)的详解
2013/05/07 Javascript
javascript页面渲染速度测试脚本分享
2014/04/15 Javascript
javascript 数组操作详解
2015/01/29 Javascript
Bootstrap组件系列之福利篇几款好用的组件(推荐)
2016/06/23 Javascript
AngularJS通过ng-route实现基本的路由功能实例详解
2016/12/13 Javascript
微信小程序 缓存(本地缓存、异步缓存、同步缓存)详解
2017/01/17 Javascript
js判断手机系统是android还是ios
2017/03/07 Javascript
基于jquery实现二级联动效果
2017/03/30 jQuery
微信小程序商城项目之购物数量加减(3)
2017/04/17 Javascript
基于JavaScript实现无限加载瀑布流
2017/07/21 Javascript
Vue 配合eiement动态路由,权限验证的方法
2018/09/26 Javascript
vue项目环境变量配置的实现方法
2018/10/12 Javascript
Django框架模板介绍
2019/01/15 Python
python TF-IDF算法实现文本关键词提取
2019/05/29 Python
Python使用pyautocad+openpyxl处理cad文件示例
2019/07/11 Python
使用Python构造hive insert语句说明
2020/06/06 Python
用python实现名片管理系统
2020/06/18 Python
新手常见Python错误及异常解决处理方案
2020/06/18 Python
Python字节单位转换(将字节转换为K M G T)
2021/03/02 Python
免费获得微软MCSD证书赶快行动吧!
2012/11/13 HTML / CSS
html5适合移动应用开发的12大特性
2014/03/19 HTML / CSS
美国女性卫生用品公司:Thinx
2017/06/30 全球购物
小蚁科技官方商店:YI Technology
2019/08/23 全球购物
草莓网中国:StrawberryNet中国
2020/08/17 全球购物
凌阳科技股份有限公司C++程序员面试题笔试题
2014/11/20 面试题
初中生学习的自我评价
2013/11/14 职场文书
档案管理员岗位职责
2013/12/01 职场文书
信用社竞聘演讲稿
2014/05/16 职场文书
Java获取e.printStackTrace()打印的信息方式
2021/08/07 Java/Android
Python 数据可视化神器Pyecharts绘制图像练习
2022/02/28 Python