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利用beautifulSoup实现爬虫
Sep 29 Python
Python写的服务监控程序实例
Jan 31 Python
Python实现的Google IP 可用性检测脚本
Apr 23 Python
Python2.7基于淘宝接口获取IP地址所在地理位置的方法【测试可用】
Jun 07 Python
python递归打印某个目录的内容(实例讲解)
Aug 30 Python
python模块之paramiko实例代码
Jan 31 Python
Python通过调用有道翻译api实现翻译功能示例
Jul 19 Python
python 产生token及token验证的方法
Dec 26 Python
Python3使用Matplotlib 绘制精美的数学函数图形
Apr 11 Python
Python的Lambda函数用法详解
Sep 03 Python
jupyter notebook 的工作空间设置操作
Apr 20 Python
PyCharm中关于安装第三方包的三个建议
Sep 17 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
php adodb分页实现代码
2009/03/19 PHP
php中读写文件与读写数据库的效率比较分享
2013/10/19 PHP
PHP基于接口技术实现简单的多态应用完整实例
2017/04/26 PHP
php文件上传类的分享
2017/07/06 PHP
php设计模式之策略模式实例分析【星际争霸游戏案例】
2020/03/26 PHP
如何在PHP中使用AES加密算法加密数据
2020/06/24 PHP
ie和firefox中img对象区别的困惑
2006/12/27 Javascript
用javascript实现页面打印的三种方法
2007/03/05 Javascript
CSS JavaScript 实现菜单功能 改进版
2008/12/09 Javascript
用JQuery 实现AJAX加载XML并解析的脚本
2009/07/25 Javascript
javaScript 判断字符串是否为数字的简单方法
2009/07/25 Javascript
添加JavaScript重载函数的辅助方法2
2010/07/04 Javascript
JavaScript闭包函数访问外部变量的方法
2014/08/27 Javascript
JS实现网页背景颜色与select框中颜色同时变化的方法
2015/02/27 Javascript
javascript实现类似于新浪微博搜索框弹出效果的方法
2015/07/27 Javascript
ionic实现可滑动的tab选项卡切换效果
2020/04/15 Javascript
jQuery动态改变多行文本框高度的方法
2016/09/07 Javascript
详解vue挂载到dom上会发生什么
2019/01/20 Javascript
javascript如何使用函数random来实现课堂随机点名方法详解
2020/07/28 Javascript
[01:51]历届DOTA2国际邀请赛举办地回顾 TI9落地上海
2018/08/26 DOTA
python使用pymysql实现操作mysql
2016/09/13 Python
python正则中最短匹配实现代码
2018/01/16 Python
python使用PIL给图片添加文字生成海报示例
2018/08/17 Python
pyqt5 使用cv2 显示图片,摄像头的实例
2019/06/27 Python
通过python改变图片特定区域的颜色详解
2019/07/15 Python
python实现大学人员管理系统
2019/10/25 Python
Django 允许局域网中的机器访问你的主机操作
2020/05/13 Python
matplotlib.pyplot.plot()参数使用详解
2020/07/28 Python
Python实现中英文全文搜索的示例
2020/12/04 Python
西班牙购买行李箱和背包网站:Maletas Greenwich
2019/10/08 全球购物
年会主持词结束语
2014/03/27 职场文书
承诺书模板大全
2015/05/04 职场文书
幼儿园圣诞节活动总结
2015/05/06 职场文书
少先队中队工作总结
2015/08/14 职场文书
八年级地理课件资料及考点知识分享
2019/08/30 职场文书
在 SQL 语句中处理 NULL 值的方法
2021/06/07 SQL Server