这篇文章主要介绍了python多进程并发demo实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
前言
下午需要简单处理一份数据,就直接随手写脚本处理了,但发现效率太低,速度太慢,就改成多进程了;
程序涉及计算、文件读写,鉴于计算内容挺多的,就用多进程了(计算密集)。
代码
import pandas as pd
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor
parse_path = '/data1/v-gazh/CRSP/dsf_full_fields/parse'
source_path = '/data1/v-gazh/CRSP/dsf_full_fields/2th_split' # 目录中有3.3W个csv文件,串行的话,效率大打折扣
def parseData():
source_path_list = list(Path(source_path).glob('*.csv'))
multi_process = ProcessPoolExecutor(max_workers=20)
multi_results = multi_process.map(func, source_path_list)
def func(p):
source_p = str(p)
parse_p = str(p).replace('2th_split', 'parse')
df = pd.read_csv(source_p)
df['date'] = pd.to_datetime(df['date'].astype(str)).dt.date
df.sort_values(['date'], inplace=True)
# 处理close为负的值(abs),添加status标识
df['is_close'] = df['PRC'].map(lambda x: 0 if x < 0 or pd.isna(x) else 1)
df['PRC'] = df['PRC'].abs()
df.rename(columns={'CFACPR': 'factor'}, inplace=True)
df['adj_low'] = df['BIDLO'] * df['factor']
df['adj_high'] = df['ASKHI'] * df['factor']
df['adj_close'] = df['PRC'] * df['factor']
df['adj_open'] = df['OPENPRC'] * df['factor']
df['adj_volume'] = df['VOL'] / df['factor']
# calc change
df['change'] = df['adj_close'].diff(1) / df['adj_close'].shift(1) df.drop_duplicates(inplace=True)
df.to_csv(parse_p, index=False)
parseData()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
时间: 2019-12-12