{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Dataflows Tutorial\n", "\n", "This tutorial is built as a Jupyter notebook which allows you to run and modify the code inline and can be used as a starting point for new Dataflows projects.\n", "\n", "To get started quickly without any installation, click here: [![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/datahq/dataflows/master?filepath=TUTORIAL.ipynb)\n", "\n", "If you want, you can just skip the installation section and follow the tutorial as-is, copy-pasting the relevant code example to your Python interpreter.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Installation\n", "\n", "Easiest way to get started on any OS is to [Download and install the latest Python 3.7 Miniconda distribution](https://conda.io/miniconda.html)\n", "\n", "Open a terminal with Miniconda (or Anaconda) and run the following to create a environment:\n", "\n", "```sh\n", "conda create -n dataflows 'python>=3.7' jupyter jupyterlab ipython leveldb\n", "```\n", "\n", "Activate the environment and install dataflows:\n", "\n", "```sh\n", ". activate dataflows\n", "pip install -U dataflows[speedup]\n", "```\n", "\n", "The above command installs Dataflows optimized for speed, if you encounter problems installing it, install without the `[speedup]` suffix.\n", "\n", "Save the tutorial notebook in current working directory (right-click and save on following link): https://raw.githubusercontent.com/datahq/dataflows/master/TUTORIAL.ipynb\n", "\n", "Start Jupyter Lab:\n", "\n", "```sh\n", "jupyter lab\n", "```\n", "\n", "Double-click the tutorial notebook you downloaded from the sidebar of Jupyter Lab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Learn how to write your own processing flows\n", "\n", "Let's start with the traditional 'hello, world' example:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[{'data': 'hello'}, {'data': 'world'}]]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow\n", "\n", "data = [\n", " {'data': 'Hello'},\n", " {'data': 'World'}\n", "]\n", "\n", "def lowerData(row):\n", " row['data'] = row['data'].lower()\n", "\n", "Flow(\n", " data,\n", " lowerData\n", ").results()[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This very simple flow takes a list of `dict`s and applies a row processing function on each one of them.\n", "\n", "We can load data from a file instead:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%writefile beatles.csv\n", "name,instrument \n", "john,guitar\n", "paul,bass\n", "george,guitar\n", "ringo,drums" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[{'name': 'John', 'instrument': 'guitar'},\n", " {'name': 'Paul', 'instrument': 'bass'},\n", " {'name': 'George', 'instrument': 'guitar'},\n", " {'name': 'Ringo', 'instrument': 'drums'}]]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, load\n", "\n", "def titleName(row):\n", " row['name'] = row['name'].title()\n", "\n", "Flow(\n", " load('beatles.csv'),\n", " titleName\n", ").results()[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The source file can be a CSV file, an Excel file or a Json file. You can use a local file name or a URL for a file hosted somewhere on the web.\n", "\n", "Data sources can be generators and not just lists or files. Let's take as an example a very simple scraper:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from dataflows import Flow, printer\n", "\n", "from lxml import etree\n", "from urllib.request import urlopen\n", "\n", "def country_population():\n", " \"\"\"Get from Wikipedia the population count for each country.\"\"\"\n", " # Read the Wikipedia page and parse it using etree\n", " page = urlopen('https://en.wikipedia.org/w/index.php?title=List_of_countries_and_dependencies_by_population&oldid=987469839').read()\n", " parser = etree.XMLParser(recover=True)\n", " tree = etree.fromstring(page, parser)\n", " # Iterate on all tables, rows and cells\n", " for table in tree.findall('.//table'):\n", " if 'wikitable' in table.attrib.get('class', ''):\n", " for row in table.find('tbody').findall('tr'):\n", " cells = row.findall('td')\n", " if len(cells) > 3:\n", " # If a matching row is found...\n", " name = cells[0].find('.//a').attrib.get('title').replace(\"Demographics of\",\"\")\n", " population = cells[1].text\n", " # ... yield a row with the information\n", " yield dict(\n", " name=name,\n", " population=population\n", " )\n", "\n", "Flow(\n", " country_population(),\n", " printer(num_rows=1, tablefmt='html')\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is nice, but we do prefer the numbers to be actual numbers and not strings.\n", "\n", "In order to do that, let's simply define their type to be numeric and truncate to millions:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "

res_1

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
# name\n", "(string) population\n", "(number)
1 Demographics of China 1402.32
2 Demographics of India 1361.34
...
241Demographics of Pitcairn Islands 5e-05
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "{}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, set_type\n", "\n", "Flow(\n", " country_population(),\n", " set_type('population', type='number', groupChar=','),\n", " lambda row: dict(row, population=row['population']/1000000),\n", " printer(num_rows=1, tablefmt='html')\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Data is automatically converted to the correct native Python type.\n", "\n", "Apart from data-types, it's also possible to set other constraints to the data. If the data fails validation (or does not fit the assigned data-type) an exception will be thrown - making this method highly effective for validating data and ensuring data quality. \n", "\n", "What about large data files? In the above examples, the results are loaded into memory, which is not always preferable or acceptable. In many cases, we'd like to store the results directly onto a hard drive - without having the machine's RAM limit in any way the amount of data we can process.\n", "\n", "We do it by using _dump_ processors:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'count_of_rows': 241,\n", " 'bytes': 9568,\n", " 'hash': '91728bdcca916272c69747ea89eea3d6',\n", " 'dataset_name': None}" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, set_type, dump_to_path\n", "\n", "Flow(\n", " country_population(),\n", " set_type('population', type='number', groupChar=','),\n", " dump_to_path('country_population')\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Running this code will create a local directory called `country_population`, containing two files:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "country_population/datapackage.json\n", "country_population/res_1.csv\n" ] } ], "source": [ "import glob\n", "print(\"\\n\".join(glob.glob('country_population/*')))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The CSV file - `res_1.csv` - is where the data is stored. The `datapackage.json` file is a metadata file, holding information about the data, including its schema.\n", "\n", "We can now open the CSV file with any spreadsheet program or code library supporting the CSV format - or using one of the **data package** libraries out there, like so:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'name': 'Demographics of China', 'population': Decimal('1402320560')}\n" ] } ], "source": [ "from datapackage import Package\n", "pkg = Package('country_population/datapackage.json')\n", "it = pkg.resources[0].iter(keyed=True)\n", "print(next(it))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note how using the data package meta-data, data-types are restored and there's no need to 're-parse' the data. This also works with other types too, such as dates, booleans and even `list`s and `dict`s.\n", "\n", "So far we've seen how to load data, process it row by row, and then inspect the results or store them in a data package.\n", "\n", "Let's see how we can do more complex processing by manipulating the entire data stream:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "

res_1

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
# a\n", "(integer) b\n", "(integer) c\n", "(integer)
1 3 4 5
2 51213
...
6 121620
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "{'count_of_rows': 6,\n", " 'bytes': 1103,\n", " 'hash': '81ce126294657c5f0a722803e86eb6f8',\n", " 'dataset_name': None}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, set_type, dump_to_path, printer\n", "\n", "# Generate all triplets (a,b,c) so that 1 <= a <= b < c <= 20\n", "def all_triplets():\n", " for a in range(1, 20):\n", " for b in range(a, 20):\n", " for c in range(b + 1, 21):\n", " yield dict(a=a, b=b, c=c)\n", "\n", "\n", "# Yield row only if a^2 + b^2 == c^1\n", "def filter_pythagorean_triplets(rows):\n", " for row in rows:\n", " if row[\"a\"] ** 2 + row[\"b\"] ** 2 == row[\"c\"] ** 2:\n", " yield row\n", "\n", "\n", "Flow(\n", " all_triplets(),\n", " set_type('a', type='integer'),\n", " set_type('b', type='integer'),\n", " set_type('c', type='integer'),\n", " filter_pythagorean_triplets,\n", " dump_to_path('pythagorean_triplets'),\n", " printer(num_rows=1, tablefmt='html')\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `filter_pythagorean_triplets` function takes an iterator of rows, and yields only the ones that pass its condition. \n", "\n", "The flow framework knows whether a function is meant to handle a single row or a row iterator based on its parameters: \n", "\n", "- If it accepts a single `row` parameter, then it's a row processor.\n", "- If it accepts a single `rows` parameter, then it's a rows processor.\n", "- If it accepts a single `package` parameter, then it's a package processor.\n", "\n", "Let's see a few examples of what we can do with a package processor.\n", "\n", "First, let's add a field to the data:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "

beatles

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
# name\n", "(string) instrument\n", "(string) is_guitarist\n", "(boolean)
1 john guitarTrue
2 paul bass False
...
4 ringodrums False
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "{'count_of_rows': 4,\n", " 'bytes': 1175,\n", " 'hash': '27b1a87d3fee5fc5d8dd667cec129107',\n", " 'dataset_name': None}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, load, dump_to_path, printer\n", "\n", "\n", "def add_is_guitarist_column_to_schema(package):\n", " # Add a new field to the first resource\n", " package.pkg.descriptor[\"resources\"][0][\"schema\"][\"fields\"].append(\n", " dict(name=\"is_guitarist\", type=\"boolean\")\n", " )\n", " # Must yield the modified datapackage\n", " yield package.pkg\n", " # And its resources\n", " yield from package\n", "\n", "\n", "def add_is_guitarist_column(row):\n", " row['is_guitarist'] = row['instrument'] == 'guitar'\n", "\n", "Flow(\n", " # Same one as above\n", " load('beatles.csv'),\n", " add_is_guitarist_column_to_schema,\n", " add_is_guitarist_column,\n", " dump_to_path('beatles_guitarists'),\n", " printer(num_rows=1, tablefmt='html')\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example we create two steps: one for adding the new field (`is_guitarist`) to the schema and another step to modify the actual data.\n", "\n", "We can combine the two into one step:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/html": [ "

beatles

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
# name\n", "(string) instrument\n", "(string) is_guitarist\n", "(boolean)
1 john guitarTrue
2 paul bass False
...
4 ringodrums False
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "{'count_of_rows': 4,\n", " 'bytes': 1175,\n", " 'hash': '27b1a87d3fee5fc5d8dd667cec129107',\n", " 'dataset_name': None}" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, load, dump_to_path\n", "\n", "\n", "def add_is_guitarist_column(package):\n", "\n", " # Add a new field to the first resource\n", " package.pkg.descriptor[\"resources\"][0][\"schema\"][\"fields\"].append(\n", " dict(name=\"is_guitarist\", type=\"boolean\")\n", " )\n", " # Must yield the modified datapackage\n", " yield package.pkg\n", "\n", " # Now iterate on all resources\n", " resources = iter(package)\n", " # Take the first resource\n", " beatles = next(resources)\n", "\n", " # And yield it with with the modification\n", " def f(row):\n", " row['is_guitarist'] = row['instrument'] == 'guitar'\n", " return row\n", "\n", " yield map(f, beatles)\n", "\n", "Flow(\n", " # Same one as above\n", " load('beatles.csv'),\n", " add_is_guitarist_column,\n", " dump_to_path('beatles_guitarists'),\n", " printer(num_rows=1, tablefmt='html')\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The contract for the `package` processing function is simple:\n", "\n", "First, modify `package.pkg` (which is a `Package` instance) and yield it.\n", "\n", "Then, yield any resources that should exist on the output, with or without modifications.\n", "\n", "In the next example we're removing an entire resource in a package processor - this next one filters the list of Academy Award nominees to those who won both the Oscar and an Emmy award:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "saving checkpoint to: .checkpoints/emmy-academy-nominees-winners\n" ] }, { "data": { "text/html": [ "

oscars

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
# Year\n", "(string) Ceremony\n", "(integer)Award\n", "(string) Winner\n", "(string)Name\n", "(string) Film\n", "(string)
1 1931/1932 5Actress 1Helen Hayes The Sin of Madelon Claudet
2 1932/1933 6Actress 1Katharine HepburnMorning Glory
...
2692015 88Honorary Award1Gena Rowlands None
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "checkpoint saved: emmy-academy-nominees-winners\n" ] }, { "data": { "text/plain": [ "{'count_of_rows': 269,\n", " 'bytes': 19027,\n", " 'hash': '9aeffeec1baa861cac7316445b796b62',\n", " 'dataset_name': None}" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, load, dump_to_path, checkpoint, printer\n", "\n", "\n", "def find_double_winners(package):\n", "\n", " # Remove the emmies resource - \n", " # we're going to consume it now\n", " package.pkg.remove_resource('emmies')\n", " # Must yield the modified datapackage\n", " yield package.pkg\n", "\n", " # Now iterate on all resources\n", " resources = iter(package)\n", "\n", " # Emmies is the first - \n", " # read all its data and create a set of winner names\n", " emmy = next(resources)\n", " emmy_winners = set(\n", " map(lambda x: x[\"nominee\"], filter(lambda x: x[\"winner\"], emmy))\n", " )\n", "\n", " # Oscars are next - \n", " # filter rows based on the emmy winner set\n", " academy = next(resources)\n", " yield filter(\n", " lambda row: (row[\"Winner\"] and row[\"Name\"] in emmy_winners), academy\n", " )\n", " \n", " # important to deque generators to ensure finalization steps of previous processors are executed\n", " yield from resources\n", "\n", "Flow(\n", " # Emmy award nominees and winners\n", " load(\n", " \"https://raw.githubusercontent.com/datahq/dataflows/master/data/emmy.csv\",\n", " name=\"emmies\",\n", " ),\n", " # Academy award nominees and winners\n", " load(\n", " \"https://raw.githubusercontent.com/datahq/dataflows/master/data/academy.csv\",\n", " encoding=\"utf8\",\n", " name=\"oscars\",\n", " ),\n", " # save a checkpoint so we won't have to re-download the source data each time\n", " checkpoint(\"emmy-academy-nominees-winners\"),\n", " find_double_winners,\n", " dump_to_path(\"double_winners\"),\n", " printer(num_rows=1, tablefmt=\"html\"),\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The previous flow was a bit complicated, but luckily we have the `join`, `concatenate` and `filter_rows` processors which make such combinations a snap:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "using checkpoint data from .checkpoints/emmy-academy-nominees-winners\n" ] }, { "data": { "text/html": [ "

oscars

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
# Year\n", "(string) Ceremony\n", "(integer)Award\n", "(string) Winner\n", "(string)Name\n", "(string) Film\n", "(string)
1 1931/1932 5Actress 1Helen Hayes The Sin of Madelon Claudet
2 1932/1933 6Actress 1Katharine HepburnMorning Glory
...
98 2015 88Honorary Award1Gena Rowlands
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "{'count_of_rows': 98,\n", " 'bytes': 6921,\n", " 'hash': '902088336aa4aa4fbab33446a241b5de',\n", " 'dataset_name': None}" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import (\n", " Flow,\n", " load,\n", " dump_to_path,\n", " join,\n", " concatenate,\n", " filter_rows,\n", " printer,\n", " checkpoint,\n", ")\n", "\n", "Flow(\n", " # load from the checkpoint we saved in the previous flow\n", " checkpoint('emmy-academy-nominees-winners'),\n", " filter_rows(equals=[dict(winner=1)], resources=['emmies']),\n", " concatenate(\n", " dict(emmy_nominee=['nominee'],),\n", " dict(name='emmies_filtered'),\n", " resources='emmies'\n", " ),\n", " join(\n", " 'emmies_filtered', ['emmy_nominee'], # Source resource\n", " 'oscars', ['Name'], # Target resource\n", " full=False # Don't add new fields, remove unmatched rows\n", " ),\n", " filter_rows(equals=[dict(Winner='1')]),\n", " dump_to_path('double_winners'),\n", " printer(num_rows=1, tablefmt='html')\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Builtin Processors\n", "\n", "DataFlows comes with a few built-in processors which do most of the heavy lifting in many common scenarios, leaving you to implement only the minimum code that is specific to your specific problem.\n", "\n", "A complete list, which also includes an API reference for each one of them, can be found in the [Built-in Processors](https://github.com/datahq/dataflows/blob/master/PROCESSORS.md#builtin-processors) page.\n", "\n", "## Nested Flows\n", "\n", "The flow object itself can be used as a step in another flow, this allows for useful design patterns which promote code reusability and readability:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* A R\n", "* * R\n", "* * *\n", "* A X\n", "* * X\n", "* * *\n" ] }, { "data": { "text/plain": [ "{}" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dataflows import Flow, printer\n", "\n", "# generate a customizable, predefined flow\n", "def text_processing_flow(star_letter_idx):\n", "\n", " # run upper on all cell values\n", " def upper(row):\n", " for k in row:\n", " row[k] = row[k].upper()\n", " \n", " # star the letter at the index from star_letter_idx argument\n", " def star_letter(row):\n", " for k in row:\n", " s = list(row[k])\n", " s[star_letter_idx] = \"*\"\n", " row[k] = \"\".join(s)\n", " \n", " def print_foo(row):\n", " print(\" \".join(list(row[\"foo\"])))\n", "\n", " return Flow(upper, star_letter, print_foo)\n", "\n", "Flow(\n", " [{\"foo\": \"bar\"}, {\"foo\": \"bax\"}],\n", " text_processing_flow(0),\n", " text_processing_flow(1),\n", " text_processing_flow(2),\n", ").process()[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Next Steps\n", "\n", "* [DataFlows Processors Reference](https://github.com/datahq/dataflows/blob/master/PROCESSORS.md)\n", "* [Datapackage Pipelines Tutorial](https://github.com/frictionlessdata/datapackage-pipelines/blob/master/TUTORIAL.ipynb) - Use the flows as building blocks for more complex pipelines processing systems." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }