当前位置: 首页 > 科技观察

Python高效处理大文件_0

时间:2023-03-12 04:17:46 科技观察

为了并行处理,我们将任务划分为子单元。它增加了程序处理的作业数量并减少了整体处理时间。例如,如果您正在处理一个大型CSV文件并且您想要修改单个列。我们将数据作为数组输入函数,它会同时并行处理多个值,具体取决于可用进程的数量。这些过程基于处理器中的内核数量。在这篇文章中,我们将学习如何使用multiprocessing、joblib和tq??dmPython包减少大文件的处理时间。这是一个简单的教程,可以应用于任何文件、数据库、图像、视频和音频。首先,我们将使用来自Kaggle的美国事故(2016-2021)数据集,该数据集包含280万条记录和47列。https://www.kaggle.com/datasets/sobhanmoosavi/us-accidents我们将导入multiprocessing,joblib和tq??dm用于并行处理,pandas用于数据导入,re,nltk和string用于文本处理。#并行计算importmultiprocessingasmpfromjoblibimportParallel,delayedfromtqdm.notebookimporttqdm#DataIngestionimportpandasaspd#TextProcessingimportrefromnltk.corpusimportstopwordsimportstring在我们开始之前,让我们通过加倍cpu_count()。如您所见,我们有8个工人。n_workers=2*mp.cpu_count()print(f"{n_workers}workersareavailable")>>>8workersareavailable接下来,我们将使用pandasread_csv函数读取大型CSV文件。然后打印出数据框的形状、列的名称和处理时间。%%timefile_name="../input/us-accidents/US_Accidents_Dec21_updated.csv"df=pd.read_csv(file_name)print(f"形状:{df.shape}\n\n列名称:\n{df.columns}\n")输出:Shape:(2845342,47)ColumnNames:Index(['ID','Severity','Start_Time','End_Time','Start_Lat','Start_Lng','End_Lat','End_Lng','Distance(mi)','Description','Number','Street','Side','City','County','State','Zipcode','Country','Timezone','Airport_Code','Weather_Timestamp','温度(F)','Wind_Chill(F)','湿度(%)','压力(in)','能见度(mi)','Wind_Direction','Wind_Speed(mph)','降水(in)','Weather_Condition','Amenity','Bump','Crossing','Give_Way','Junction','No_Exit','Railway','Roundabout','Station','Stop','Traffic_Calming','Traffic_Signal','Turning_Loop','Sunrise_Sunset','Civil_Twilight','Nautical_Twilight','Astronomical_Twilight'],dtype='object')CPU时间:用户33.9秒,系统:3.93秒,total:37.9sWalltime:46.9s处理文本clean_text是一个用于处理文本的简单函数。我们将使用nltk.copus获取英文停用词,并使用它来过滤掉一行文本中的停用词。之后,我们将删除句子中的特殊字符和多余空格。它将成为确定串行、并行和批处理的处理时间的基准函数。defclean_text(text):#删除停用词stops=stopwords.words("english")text="".join([wordforwordintext.split()ifwordnotinstops])#删除特殊字符text=text.translate(str.maketrans('','',string.punctuation))#去掉多余的空格text=re.sub('+','',text)returntext串行处理对于串行处理,我们可以使用pandas.apply()函数,但是如果你想看到进度条,你需要为pandas激活tqdm,然后使用.progress_apply()函数。我们将处理280万条记录并将结果保存回“描述”列。%%timetqdm.pandas()df['Description']=df['Description'].progress_apply(clean_text)output高端处理器串行处理280万行耗时9分5秒。100%