{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Making a subset of the data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this notebook, we create a subset of the NYC taxi dataset. This subset only contains 0.5% of all rows." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Instructions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* It is recommended to have **100GB of free space** on your hard drive.\n", "* This notebook should be in the `minibook-2nd-code/chapter2/cleaning/` directory.\n", "* The original data files should be in the `minibook-2nd-code/chapter2/data/` directory.\n", "* The 24 data files are named `trip_data_1.csv.zip`, ..., `trip_fare_1.csv.zip`. **Make sure to download these files and put them in the `data` directory**.\n", "* This notebook will create two `trip_data_subset.csv` and `trip_fare_subset.csv` files in the `data` directory.\n", "* Once the 24 data files have been put in `data/`, click on `Cell > Run all` above to launch the extraction process. **It will take several minutes**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The procedure implemented here is memory-efficient in that the full ZIP files are not first extracted on disk. Unzipping occurs on the fly. We make heavy use of Python generators and iterators." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Relative path of the directory containing the data.\n", "data_dir = '../data'\n", "# Only keep one out of 'step' lines ('200' = 0.5%).\n", "step = 200\n", "# In every file, stop after 'stop' lines (None=until the end).\n", "stop = None # type 400 to test the script and generate tiny subsets." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import os\n", "import os.path as op\n", "import re\n", "import zipfile\n", "import glob\n", "from itertools import chain, islice" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def _csv_filename(zip_filename):\n", " \"\"\"Return the filename of the CSV in a ZIP file.\"\"\"\n", " return op.splitext(op.basename(zip_filename))[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def _iter_lines(zip_filename):\n", " \"\"\"Iterate over all rows from a zipped CSV file.\"\"\"\n", " print(\"Processing file {file}...\".format(file=zip_filename))\n", " csv_filename = _csv_filename(zip_filename)\n", " with zipfile.ZipFile(zip_filename) as z:\n", " with z.open(csv_filename) as f:\n", " for line in f:\n", " yield line" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def _iter_all_lines(files, step=None, stop=None):\n", " \"\"\"Iterate over rows from several zipped CSV files.\"\"\"\n", " # Keep the header row in the first file, but not in the other files.\n", " return chain(*[islice(_iter_lines(f), min(1, i), stop, step)\n", " for i, f in enumerate(files)])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def _extract_number(filename):\n", " \"\"\"Return the month number appearing in a ZIP file.\"\"\"\n", " r = re.search(r'([\\d]+)', filename)\n", " if r:\n", " return int(r.group(1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def _zip_filenames(name):\n", " \"\"\"Return the ordered list of ZIP filenames.\"\"\"\n", " return sorted(glob.glob(op.join(data_dir, 'trip_{name}_*.zip'.format(name=name))), \n", " key=_extract_number)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def _make_extract(step=None, stop=None):\n", " \"\"\"Create the subset data.\"\"\"\n", " for name in ('fare', 'data'):\n", " # Output CSV filename (with the subset data).\n", " filename = op.join(data_dir, 'trip_{name}_subset.csv'.format(name=name))\n", " # List of zipped CSV files.\"\n", " files = _zip_filenames(name)\n", " with open(filename, 'wb') as f:\n", " # Iterate over a subset of the rows from all files.\n", " for line in _iter_all_lines(files, step=step, stop=stop):\n", " f.write(line)\n", " print(\"*** Done! {0} has been successfully created. ***\\n\".format(filename))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Make the subset data (**this will take a while**)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [], "source": [ "_make_extract(step=step, stop=stop)" ] } ], "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.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }