Skip to main content
BIG DATA ANALYTICS WITH PYTHON
ENSEA, Abidjan, Côte d’Ivoire · 30 November – 4 December 2026
<span style="background: #F2A65A; color: #14213D; font-weight: 700; font-size: 13px; padding: 4px 10px; border-radius: 12px;">Module 2 · Parallel and Distributed Computing</span>
<span style="background: #D7E6E4; color: #14213D; font-weight: 600; font-size: 13px; padding: 4px 10px; border-radius: 12px; margin-left: 6px;">⏱ about TODO minutes</span>

Parallel Processing in Python

Objective Speed up work on large data with pandas reading options and Python’s built-in multiprocessing library.
You will Read a large CSV in chunks or by column · Run a function in parallel with multiprocessing.Pool · Compare sequential and parallel running times
Data data/raw/activity_log_raw.csv (8.3 GB, USB drive) · data/raw/synthetic-cdrs/ (~12.5 GB, USB drive)
Core packages multiprocessing · pandas · plotly

In this tutorial, you will learn how to use the Python builtin Multiprocessing library to parallelize computations. This is often one of the first step when dealing large computations. We will cover the following:

  • Using Multiprocessing with a single parameter function
  • Using Multiprocessing with multiple parameters function
  • Use joblib library for paralellizing functions
  • Other ways to parallelize functions in Python

For more technical details about the multiprocessing library, please see the documentation here

Open In Colab
Requirements: pandas, seaborn, plotly.
Data: a large CSV file in data/raw/ (see data/README.md).

# Standard library: parallel processing, timing and paths
#import asyncio
import time
from multiprocessing import Pool
from pathlib import Path

# Data and plotting
#import aiohttp
import pandas as pd
import plotly as px
import seaborn as sns

0. Setup and Configuration

Working Directory and Input Files

# ============================================================
# BASE WORKING DIRECTORIES
# ============================================================
# The course folder is the closest folder, going upwards, that contains environment.yml
DIR_COURSE = next(
    (p for p in [Path.cwd(), *Path.cwd().parents] if (p / "environment.yml").exists()), None
)
if DIR_COURSE is None:
    DIR_COURSE = Path.cwd()
    print("Running outside the course folder (e.g. Colab): upload the datasets to data/raw/.")
DIR_DATA = DIR_COURSE / "data" / "raw"

# ============================================================
# INPUT FILES
# ============================================================
# Activity log (large CSV, 8.3 GB)
FILE_ACTIVITY_LOG = DIR_DATA / "activity_log_raw.csv"

# Synthetic call detail records (folder of ~10,000 CSV files) and one of its files
DIR_CDRS = DIR_DATA / "synthetic-cdrs"
FILE_CDR_SAMPLE = DIR_CDRS / "HW2018062913016546.dat.csv"

# ============================================================
# OUTPUT FOLDERS
# ============================================================
DIR_MANY_CSV_FILES = DIR_DATA / "many-csv-files"

Global Variables for Processing

# ============================================================
# SETTINGS
# ============================================================
# None defined yet.

Optimizing Pandas

Read only a subset of the rows

# you can reeplace this with activity_log_raw.csv file or the kaggle-expedia-train.csv
file_16gb = FILE_ACTIVITY_LOG
df_first_5mill = pd.read_csv(file_16gb, nrows=200000)

Read data in chunks

# set chunck size to 5 million rows
chunksize = 2000000
cnt = 1
tot_rows = 0
dataframe_list = []
with pd.read_csv(file_16gb, chunksize=chunksize) as reader:
    # Do some processing with those two million rows
    for chunk in reader:
        print("Working on chunk: {}".format(cnt))
        print(chunk.shape)
        tot_rows += chunk.shape[0]
        dataframe_list.append(chunk)
        cnt += 1
        if cnt == 10:
            break

Read only a subset of columns

With pandas, you can also read a subset of the columns instead reading all columns.

EXERCISE-1: Which arguement do you use to read only a subset of columns in pandas?

# Replace these with column names from the CSV file you are using
df = pd.read_csv(file_16gb, usecols=['PROVINCE', 'REGION', 'DISTRICT', 'COMMUNES', 'MILIEU'])
df

Speeding up IO Bound Programs

Refer to this Python script for this.

Using multiprocessing with a single parameter function

1. Define function we would like to run

For the sake demonstration here, we will define a very simple function.

def square(num):
    return num**2

Run the function sequentially on a big list

result = [square(x) for x in list(range(100000000))]
result

Run with multiprocessing

These lines create a multiprocessing pool of eight workers, and we can use this pool to map our required function to this list. The Pool class represents a pool of worker processes. It has methods which allows tasks to be offloaded to the worker processes in a few different ways.

# Number of logical cores/cpus/processors as opposed to physical cores
pool = Pool(6)
result = pool.map(square,list(range(100000)))
pool.close()

Compare the linear/sequential processing with the parallel processing

def run_func(list_length):
    print("Size of List:{}".format(list_length))
    t0 = time.time()
    result1 = [square(x) for x in list(range(list_length))]
    t1 = time.time()
    diff = round(t1-t0, 4)
    print("Running time-Sequential Processing: {} seconds".format(diff))
    time_without_multiprocessing = diff
    # Run with multiprocessing
    t0 = time.time()
    pool = Pool(8)
    result2 = pool.map(square,list(range(list_length)))
    pool.close()
    t1 = time.time()
    diff = round(t1-t0, 4)
    print("Running time-Multiprocessing: {} seconds".format(diff))
    time_with_multiprocessing = diff
    return time_without_multiprocessing, time_with_multiprocessing
def main():
    times_taken = []
    for i in range(1, 9):
        list_length = 10**i
        time_seq, time_parallel = run_func(list_length)
        times_taken.append([list_length, 'No Multiproc', time_seq])
        times_taken.append([list_length, 'Multiproc', time_parallel])

    timedf = pd.DataFrame(times_taken,columns = ['list_length', 'type','time_taken'])
    fig =  px.line(timedf,x = 'List-Length',y='Timetaken',color='type',log_x=True)
    plotly.offline.plot(fig, filename='comparison_bw_multiproc.html')

EXERCISE-2:

  1. Make the function 3 seconds slower and report what happens. Hint. You can use time.sleep(seconds) to simulate a more tie consumning function.
  2. Find out the number of logical processors on your machine
  3. Reduce the number of processors available to Pool and see if it has effect on the running time.

Using multiprocessing with multiple parameter function

We can extend the code above to run a function with multiple parameters. We can simply use the starmap method for Pool to achieve this as below.

def square_add(num1, num2):
    return num1**2 + num2**2
folder = DIR_CDRS
df = FILE_CDR_SAMPLE
df = pd.read_csv(FILE_CDR_SAMPLE)
344/60
5.733333333333333
folder = DIR_CDRS
outdir = DIR_MANY_CSV_FILES
processors = Pool(4)
params = [[100,4],[150,5],[200,6],[300,4]]
results = processors.starmap(square_add, params)
processors.close()
print(results[2])

Other ways to utilize multiprocessing in Python

Although we have only shown simple basic examples here, you can use multiprocessing to perfom There are other libraries which can be used to achieve parallization in Python. FOr example:

  1. concurrent.futures. Although its also a builtin library, it is considered more high level and relatively easier to use than using multiprocessing directly.
  2. Joblib

Summary

  • TODO
  • TODO
  • TODO

Next: Introduction to Using APIs