Live Notebook

You can run this notebook in a live session Binder or view it on Github.

Dask Bags

Dask Bag implements operations like map, filter, groupby and aggregations on collections of Python objects. It does this in parallel and in small memory using Python iterators. It is similar to a parallel version of itertools or a Pythonic version of the PySpark RDD.

Dask Bags are often used to do simple preprocessing on log files, JSON records, or other user defined Python objects.

Full API documentation is available here:

Start Dask Client for Dashboard

Starting the Dask Client is optional. It will provide a dashboard which is useful to gain insight on the computation.

The link to the dashboard will become visible when you create the client below. We recommend having it open on one side of your screen while using your notebook on the other side. This can take some effort to arrange your windows, but seeing them both at the same is very useful when learning.

from dask.distributed import Client, progress
client = Client(n_workers=4, threads_per_worker=1)



  • Workers: 4
  • Cores: 4
  • Memory: 8.36 GB

Create Random Data

We create a random set of record data and store it to disk as many JSON files. This will serve as our data for this notebook.

import dask
import json
import os

os.makedirs('data', exist_ok=True)              # Create data/ directory

b = dask.datasets.make_people()                 # Make records of people'data/*.json')   # Encode as JSON, write to disk

Read JSON data

Now that we have some JSON data in a file lets take a look at it with Dask Bag and Python JSON module.

!head -n 2 data/0.json
{"age": 25, "name": ["Augustus", "Day"], "occupation": "Travel Agent", "telephone": "409.600.7055", "address": {"address": "313 San Ramon Bay", "city": "El Dorado"}, "credit-card": {"number": "2681 3827 7606 2006", "expiration-date": "12/22"}}
{"age": 32, "name": ["Alvaro", "Ford"], "occupation": "Nutritionist", "telephone": "1-816-561-0705", "address": {"address": "1078 Dorland Square", "city": "Monroeville"}, "credit-card": {"number": "5403 4504 4125 1591", "expiration-date": "11/18"}}
import dask.bag as db
import json

b = db.read_text('data/*.json').map(json.loads)
dask.bag<loads, npartitions=10>
({'age': 25,
  'name': ['Augustus', 'Day'],
  'occupation': 'Travel Agent',
  'telephone': '409.600.7055',
  'address': {'address': '313 San Ramon Bay', 'city': 'El Dorado'},
  'credit-card': {'number': '2681 3827 7606 2006',
   'expiration-date': '12/22'}},
 {'age': 32,
  'name': ['Alvaro', 'Ford'],
  'occupation': 'Nutritionist',
  'telephone': '1-816-561-0705',
  'address': {'address': '1078 Dorland Square', 'city': 'Monroeville'},
  'credit-card': {'number': '5403 4504 4125 1591',
   'expiration-date': '11/18'}})

Map, Filter, Aggregate

We can process this data by filtering out only certain records of interest, mapping functions over it to process our data, and aggregating those results to a total value.

b.filter(lambda record: record['age'] > 30).take(2)  # Select only people over 30
({'age': 32,
  'name': ['Alvaro', 'Ford'],
  'occupation': 'Nutritionist',
  'telephone': '1-816-561-0705',
  'address': {'address': '1078 Dorland Square', 'city': 'Monroeville'},
  'credit-card': {'number': '5403 4504 4125 1591',
   'expiration-date': '11/18'}},
 {'age': 64,
  'name': ['Izetta', 'Rosales'],
  'occupation': 'Tree Surgeon',
  'telephone': '(840) 191-0546',
  'address': {'address': '846 Balceta Side road', 'city': 'Clovis'},
  'credit-card': {'number': '2628 2918 0384 1702',
   'expiration-date': '03/25'}})
[7]: record: record['occupation']).take(2)  # Select the occupation field
('Travel Agent', 'Nutritionist')
b.count().compute()  # Count total number of records

Chain computations

It is common to do many of these steps in one pipeline, only calling compute or take at the end.

result = (b.filter(lambda record: record['age'] > 30)
           .map(lambda record: record['occupation'])
           .topk(10, key=1))
dask.bag<topk-aggregate, npartitions=1>

As with all lazy Dask collections, we need to call compute to actually evaluate our result. The take method used in earlier examples is also like compute and will also trigger computation.

[('Instrument Technician', 15),
 ('Payroll Manager', 15),
 ('Spring Maker', 14),
 ('Botanist', 14),
 ('Pool Attendant', 14),
 ('Roadworker', 13),
 ('Refractory Engineer', 13),
 ('Regulator', 13),
 ('Chartered Accountant', 13),
 ('Health Service', 13)]

Transform and Store

Sometimes we want to compute aggregations as above, but sometimes we want to store results to disk for future analyses. For that we can use methods like to_textfiles and json.dumps, or we can convert to Dask Dataframes and use their storage systems, which we’ll see more of in the next section.

(b.filter(lambda record: record['age'] > 30)  # Select records of interest
  .map(json.dumps)                            # Convert Python objects to text
  .to_textfiles('data/processed.*.json'))     # Write to local disk

Convert to Dask Dataframes

Dask Bags are good for reading in initial data, doing a bit of pre-processing, and then handing off to some other more efficient form like Dask Dataframes. Dask Dataframes use Pandas internally, and so can be much faster on numeric data and also have more complex algorithms.

However, Dask Dataframes also expect data that is organized as flat columns. It does not support nested JSON data very well (Bag is better for this).

Here we make a function to flatten down our nested data structure, map that across our records, and then convert that to a Dask Dataframe.

({'age': 25,
  'name': ['Augustus', 'Day'],
  'occupation': 'Travel Agent',
  'telephone': '409.600.7055',
  'address': {'address': '313 San Ramon Bay', 'city': 'El Dorado'},
  'credit-card': {'number': '2681 3827 7606 2006',
   'expiration-date': '12/22'}},)
def flatten(record):
    return {
        'age': record['age'],
        'occupation': record['occupation'],
        'telephone': record['telephone'],
        'credit-card-number': record['credit-card']['number'],
        'credit-card-expiration': record['credit-card']['expiration-date'],
        'name': ' '.join(record['name']),
        'street-address': record['address']['address'],
        'city': record['address']['city']
({'age': 25,
  'occupation': 'Travel Agent',
  'telephone': '409.600.7055',
  'credit-card-number': '2681 3827 7606 2006',
  'credit-card-expiration': '12/22',
  'name': 'Augustus Day',
  'street-address': '313 San Ramon Bay',
  'city': 'El Dorado'},)
df =
age occupation telephone credit-card-number credit-card-expiration name street-address city
0 25 Travel Agent 409.600.7055 2681 3827 7606 2006 12/22 Augustus Day 313 San Ramon Bay El Dorado
1 32 Nutritionist 1-816-561-0705 5403 4504 4125 1591 11/18 Alvaro Ford 1078 Dorland Square Monroeville
2 64 Tree Surgeon (840) 191-0546 2628 2918 0384 1702 03/25 Izetta Rosales 846 Balceta Side road Clovis
3 16 Recruitment Consultant 114-234-9301 2492 8469 9059 6501 02/22 Wilmer Sosa 1400 Alameda Arcade St. Cloud
4 23 Gas Mechanic +1-(859)-227-0224 2616 3576 5403 2149 07/20 Micah Duncan 847 August Gardens Peekskill

We can now perform the same computation as before, but now using Pandas and Dask dataframe.

df[df.age > 30].occupation.value_counts().nlargest(10).compute()
Payroll Manager          15
Instrument Technician    15
Pool Attendant           14
Botanist                 14
Spring Maker             14
Regulator                13
Chartered Accountant     13
Refractory Engineer      13
Roadworker               13
Health Service           13
Name: occupation, dtype: int64

Learn More

You may be interested in the following links: