cookiecutter-data-science Documentation

A logical, reasonably standardized, but flexible project structure for doing and sharing data science work.

RAW Doc

Technical Documentation: drivendataorg/cookiecutter-data-science

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

Cookiecutter Data Science

A logical, reasonably standardized but flexible project structure for doing and sharing data science work.



[](https://github.com/drivendataorg/cookiecutter-data-science/actions/workflows/tests.yml)

Cookiecutter Data Science (CCDS) is a tool for setting up a data science project template that incorporates best practices. To learn more about CCDS's philosophy, visit the project homepage.

โ„น๏ธ Cookiecutter Data Science v2 has changed from v1. It now requires installing the new cookiecutter-data-science Python package, which extends the functionality of the cookiecutter templating utility. Use the provided ccds command-line program instead of cookiecutter.

Installation

Cookiecutter Data Science v2 requires Python 3.10+. Since this is a cross-project utility application, we recommend installing it with pipx. Installation command options:

bash
# With pipx from PyPI (recommended)
pipx install cookiecutter-data-science

# With pip from PyPI
pip install cookiecutter-data-science

# With conda from conda-forge (coming soon)
# conda install cookiecutter-data-science -c conda-forge

Starting a new project

To start a new project, run:

bash
ccds

The resulting directory structure

The directory structure of your new project will look something like this (depending on the settings that you choose):

text
/* Detailed source-code truncated for AI context efficiency. */

Using unreleased changes

By default, ccds will use the project template version that corresponds to the installed ccds package version (e.g., if you have installed ccds v2.0.1, you'll use the v2.0.1 version of the project template by default). To use a specific version of the project template, use the -c/--checkout flag to provide the branch (or tag or commit hash) of the version you'd like to use. For example to use the project template from the master branch:

bash
ccds -c master

Using v1

If you want to use the old v1 project template, you need to have either the cookiecutter-data-science package or cookiecutter package installed. Then, use either command-line program with the -c v1 option:

bash
ccds https://github.com/drivendataorg/cookiecutter-data-science -c v1
# or equivalently
cookiecutter https://github.com/drivendataorg/cookiecutter-data-science -c v1

Contributing

We welcome contributions! See the docs for guidelines.

Installing development requirements

bash
pip install -r dev-requirements.txt

Running the tests

bash
pytest tests

Overview (`docs/README.md`)

Generating the docs

Install development requirements:

text
pip install -r dev-requirements.txt

Change directories into the docs folder:

text
cd docs

Use mkdocs structure to update the documentation. Test locally with:

text
mkdocs serve

The hosted docs are deployed via render when the master branch is updated.


Overview (`{{ cookiecutter.repo_name }}/README.md`)

{{cookiecutter.project_name}}

{{cookiecutter.description}}

Project Organization

text
/* Detailed source-code truncated for AI context efficiency. */


Overview (`{{ cookiecutter.repo_name }}/docs/mkdocs/README.md`)

Generating the docs

Use mkdocs structure to update the documentation.

Build locally with:

text
mkdocs build

Serve locally with:

text
mkdocs serve

Docs Index (`docs/docs/index.md`)

Cookiecutter Data Science

A logical, flexible, and reasonably standardized project structure for doing and sharing data science work.

[](https://github.com/drivendataorg/cookiecutter-data-science/actions/workflows/tests.yml)

!!! info "CCDS V2 Announcement"

text
Version 2 of Cookiecutter Data Science has launched recently. To learn more about what's different and what's in progress, see the [announcement blog post for more information](https://drivendata.co/blog/ccds-v2).

Quickstart

Cookiecutter Data Science v2 requires Python 3.10+. Since this is a cross-project utility application, we recommend installing it with pipx. Installation command options:

=== "With pipx (recommended)"

text
```bash
pipx install cookiecutter-data-science

# From the parent directory where you want your project
ccds
```

=== "With pip"

text
```bash
pip install cookiecutter-data-science
`
# From the parent directory where you want your project
ccds
```

=== "With conda (coming soon!)"

text
```bash
# conda install cookiecutter-data-science -c conda-forge

# From the parent directory where you want your project
# ccds
```

=== "Use the v1 template"

text
```bash
pip install cookiecutter

# From the parent directory where you want your project
cookiecutter https://github.com/drivendataorg/cookiecutter-data-science -c v1
```

!!! info "Use the ccds command-line tool"

text
Cookiecutter Data Science v2 now requires installing the new `cookiecutter-data-science` Python package, which extends the functionality of the [`cookiecutter`](https://cookiecutter.readthedocs.io/en/stable/README.html) templating utility. Use the provided `ccds` command-line program instead of `cookiecutter`.

Starting a new project

Starting a new project is as easy as running this command at the command line. No need to create a directory first, the cookiecutter will do it for you.

bash
ccds

The ccds commandline tool defaults to the Cookiecutter Data Science template, but you can pass your own template as the first argument if you want.

Example

Now that you've got your project, you're ready to go! You should do the following:

  • Check out the directory structure below so you know what's in the project and how to use it.
  • Read the opinions that are baked into the project so you understand best practices and the philosophy behind the project structure.
  • Read the using the template guide to understand how to get started on a project that uses the template.

Enjoy!

Directory structure

The directory structure of your new project will look something like this (depending on the settings that you choose):

text
/* Detailed source-code truncated for AI context efficiency. */

{{ Cookiecutter.Repo Name }} Docs Mkdocs Docs Getting Started (`{{ cookiecutter.repo_name }}/docs/mkdocs/docs/getting-started.md`)

Getting started

This is where you describe how to get set up on a clean install, including the
commands necessary to get the raw data (using the sync_data_from_s3 command,
for example), and then how to make the cleaned, final data sets.


{{ Cookiecutter.Repo Name }} Docs Mkdocs Docs Index (`{{ cookiecutter.repo_name }}/docs/mkdocs/docs/index.md`)

{{ cookiecutter.project_name }} documentation!

{% if cookiecutter.project_description is not none %}

Description

{{ cookiecutter.description}}
{% endif %}

Commands

The Makefile contains the central entry points for common tasks related to this project.
{% if not cookiecutter.dataset_storage.none %}

Syncing data to cloud storage

{% if cookiecutter.dataset_storage.s3 -%}

  • make sync_data_up will use aws s3 sync to recursively sync files in data/ up to s3://{{ cookiecutter.dataset_storage.s3.bucket }}/data/.
  • make sync_data_down will use aws s3 sync to recursively sync files from s3://{{ cookiecutter.dataset_storage.s3.bucket }}/data/ to data/.
    {% elif cookiecutter.dataset_storage.azure -%}
  • make sync_data_up will use az storage blob upload-batch -d to recursively sync files in data/ up to {{ cookiecutter.dataset_storage.azure.container }}/data/.
  • make sync_data_down will use az storage blob upload-batch -d to recursively sync files from {{ cookiecutter.dataset_storage.azure.container }}/data/ to data/.
    {% elif cookiecutter.dataset_storage.gcs -%}
  • make sync_data_up will use gsutil rsync to recursively sync files in data/ up to gs://{{ cookiecutter.dataset_storage.gcs.bucket }}/data/.
  • make sync_data_down will use gsutil rsync to recursively sync files in gs://{{ cookiecutter.dataset_storage.gcs.bucket }}/data/ to data/.
    {% endif %}
    {% endif %}

Mkdocs.Yml (`docs/mkdocs.yml`)

site_name: Cookiecutter Data Science
site_description: A project template and directory structure for Python data science projects.
site_url: https://cookiecutter-data-science.drivendata.org
repo_url: https://github.com/drivendataorg/cookiecutter-data-science
edit_uri: edit/master/docs/docs
copyright: Project maintained by the friendly folks at DrivenData.
theme:
favicon: favicon.ico
features:
- navigation.instant
- toc.integrate
logo: ccds.png
name: material
custom_dir: overrides
palette:
primary: custom
accent: custom
font:
text: Work Sans
code: Space Mono
nav:

  • Home: index.md
  • Why ccds?: why.md
  • Opinions: opinions.md
  • Using the template: using-the-template.md
  • All options: all-options.md
  • Contributing: contributing.md
  • Related projects: related.md
  • v1 Template: v1.md
    extra:
    analytics:
    provider: google
    property: G-DX14MC19WY
    extra_css:
  • css/extra.css
    extra_javascript:
  • js/extra.js
    markdown_extensions:
  • admonition
  • pymdownx.details
  • pymdownx.superfences
  • pymdownx.tabbed:
    alternate_style: true
    slugify: !!python/object/apply:pymdownx.slugs.slugify
    kwds:
    case: lower
  • tables
  • toc:
    toc_depth: 2
    plugins:
  • include-markdown
  • termynal:
    title: bash
    buttons: macos
    prompt_literal_start:
    - "$"
  • gen-files:
    scripts:
    - scripts/generate-termynal.py
    - scripts/configuration-table.py

Docs All Options (`docs/docs/all-options.md`)

Commandline options

CCDS provides a number of choices that you can use to customize your project. The defaults work well for many projects, but lots of tooling choices are supported. Here are the options for tools that you can use:

Checking out other branches / using unreleased changes to the template

By default, ccds will download the most recently released version of the template. If there are any unreleased changes to the template (or changes in a separate branch) that you want to incorporate, you can do so by checking out whatever branch you'd like to use (checkout master for the latest changes):

bash
ccds -c master

Docs Contributing (`docs/docs/contributing.md`)

Contributing

The Cookiecutter Data Science project is opinionated, but not afraid to be wrong. Best practices change, tools evolve, and lessons are learned. The goal of this project is to make it easier to start, structure, and share an analysis. Pull requests and filing issues is encouraged. We'd love to hear what works for you, and what doesn't.

If you use the Cookiecutter Data Science project, link back to this page or give us a holler and let us know!

Requesting New Tools

Requests for supporting new or alternative tools should be made in the discussions section of the repository. This allows for community input, upvotes, and better tracking of feature requests.


Docs Opinions (`docs/docs/opinions.md`)

Opinions

The default project structure reflects certain opinions about how to do collaborative data science work. These opinions grew out of our own experiences with what works and what doesn't. Some of these opinions are about workflows, and others are about tools that can make the process easier. These opinions are discussed below. If you have any thoughts, please contribute or share them.

Data analysis is a directed acyclic graph

Don't ever edit your raw data. Especially not manually. And especially not in Excel.

The most important features of a quality data analysis are correctness and reproducibilityโ€”anyone should be able to re-run your analysis using only your code and raw data and produce the same final products. The best way to ensure correctness is to test your analysis code. The best way to ensure reproducibility is to treat your data analysis pipeline as a directed acyclic graph (DAG). This means each step of your analysis is a node in a directed graph with no loops. You can run through the graph forwards to recreate any analysis output, or you can trace backwards from an output to examine the combination of code and data that created it.

Raw data is immutable

That proper data analysis is a DAG means that raw data must be treated as immutableโ€”it's okay to read and copy raw data to manipulate it into new outputs, but never okay to change it in place. This informs the design of the default data/ directory subfolders in which data originates from raw/ and external/, intermediate analytical outputs get serialized or cached in interim/, and final products end up in processed/ (the number or names of these folders is less important than flow of data between them).

Some dos and don'ts that follow from treating data analysis as a DAG:

  • โœ… Do write code that moves the raw data through a pipeline to your final analysis.

  • โœ… Do serialize or cache the intermediate outputs of long-running steps.

  • โœ… Do make it possible (and ideally, documented and automated) for anyone to reproduce your final data products with only the code in {{ cookiecutter.module_name }} and the data in data/raw/ (and data/external/).

  • โ›” Don't ever edit your raw data, especially not manually, and especially not in Excel. This includes changing file formats or fixing errors that might break a tool that's trying to read your data file.

  • โ›” Don't overwrite your raw data with a newly processed or cleaned version.

  • โ›” Don't save multiple versions of the raw data.

Data should (mostly) not be kept in source control

Another consequence of treating data as immutable is that data doesn't need source control in the same way that code does. Therefore, by default, the data/ folder is included in the .gitignore file. If you have a small amount of data that rarely changes, you may want to include the data in the repository. GitHub currently warns you if files are over 50MB and rejects any files over 100MB.

If you have larger amounts of data, consider storing and syncing with a cloud service like Amazon S3, Azure Blob Storage, or Google Cloud Storage. We've had a good experience with Amazon S3, if you're not tied to any particular cloud provider. Syncing tools can help you manage the data. Some examples:

There is also the Git Large File Storage (LFS) extension which lets you track large files in git but stores the files on a separate server. GitHub provides some storage compatible with Git LFS.

Tools for DAGs

DAGs are so common in data and software processes that many tools have been built to manage them. We prefer make for managing steps that depend on each other, especially the long-running ones. Make is a common tool on Unix-based platforms (and is available for Windows via chocolatey). Following the make documentation, Makefile conventions, and portability guide will help ensure your Makefiles work effectively across systems. Here are some examples to get started. A number of data folks use make as their tool of choice, including Mike Bostock.

There are other tools for managing DAGs that are written in Python, instead of their own language. Popular ones include Airflow, Luigi, Snakemake, Prefect, Dagster, and Joblib. Feel free to use these if they are more appropriate for your analysis.

Notebooks are for exploration and communication, source files are for repetition

Source code is superior for replicability because it is more portable, can be tested more easily, and is easier to code review.

Jupyter Notebook, Apache Zeppelin, and other literate programming tools are very effective for exploratory data analysis because they enable rapid iteration and visualization of results. However, these tools can be less effective for reproducing an analysis. Source code is superior for replicability because it is more portable, can be tested more easily, and is easier to code review.

When we use notebooks in our work, we often subdivide the notebooks/ folder to keep things organized and legible. For example, notebooks/exploratory/ contains initial explorations, whereas notebooks/reports/ is more polished work that can be exported as html to the reports/ directory. We also recommend that you follow a naming convention that shows the owner and the order the analysis was done in. We use the format <step>-<ghuser>-<description>.ipynb (e.g., 0.3-bull-visualize-distributions.ipynb). Since notebooks are challenging objects for source control (e.g., diffs of the json are often not human-readable and merging is near impossible), we recommended not collaborating directly with others on Jupyter notebooks. We also recommend using a tool like nbautoexport to make reviewing changes to notebooks easier.

Refactor the good parts into source code

Don't write code to do the same task in multiple notebooks. If it's a data preprocessing task, put it in the pipeline at {{ cookiecutter.module_name }}/data/make_dataset.py and load data from data/interim/. If it's useful utility code, refactor it to {{ cookiecutter.module_name }}. Classic signs that you are ready to move from a notebook to source code include duplicating old notebooks to start new ones, copy/pasting functions between notebooks, and creating object-oriented classes within notebooks.

We make it easy to refactor notebook code because the ccds template makes your project a Python package by default and installs it locally in the requirements file of your chosen environment manager. This enables you to import your project's source code and use it in notebooks with a cell like the following:

python
# OPTIONAL: Load the "autoreload" extension so that code can change
%load_ext autoreload

# OPTIONAL: always reload modules so that as you change code
# in {{ cookiecutter.module_name }}, it gets loaded
%autoreload 2

from {{ cookiecutter.module_name }}.data import make_dataset

Keep your modeling organized

Different modeling pipelines are different, so we don't provide a lot of baked-in structure to the models/ directory. However, documenting modeling experiments is critical to enable reproducibility, continuous learning, and improvement. You should implement experiment documentation procedures that enable you to, at minimum, identify the provenance of the data and the version of the code that the experiment used, as well as the metrics used to measure performance.

For smaller projects, it's fine to start with homegrown tracking using file formats like JSON that are both human- and machine-readable. You can graduate to experiment tracking tools (e.g., MLflow) if it's warranted or if they're standard for your team.

Build from the environment up

The first step in reproducing an analysis is always replicating the computational environment it was run in. You need the same tools, the same libraries, and the same versions to make everything play nicely together.

Doing so in Python requires choosing and configuring an environment management tool. The ecosystem for this tooling has evolved a lot in recent years.

For data science work, we prefer to use the conda package manager because it also manages non-Python packages, including system library dependencies that you often run into in data science. Our recommended way to install conda is with Miniforge, though the Miniconda and Anaconda installers from Anaconda are also popular.

You can also use Python-only environment managers. Popular tools in this category include virtualenv, virtualenvwrapper, Poetry, Pipenv, and others.

Cookiecutter v2 lets you pick from among many of these, or to initialize your project without one so you can roll your own.

If you have more complex requirements for recreating your environment, consider a virtual machine based approach such as Docker or Vagrant. Both of these tools use text-based formats (Dockerfile and Vagrantfile respectively) that you can easily add to source control to describe how to create a virtual machine with the requirements you need. You might also consider using pip-tools or conda-lock to generate a file that appropriately pins your dependencies.

Keep secrets and configuration out of version control

You really don't want to leak your AWS secret key or Postgres username and password on Githubโ€”see the Twelve Factor App principles on this point. Here's one way to do this:

Store your secrets and config variables in a special file

Create a .env file in the project root folder. Thanks to the .gitignore, this file should never get committed into the version control repository. Here's an example:

nohighlight
# example .env file
DATABASE_URL=postgres://username:password@localhost:5432/dbname
AWS_ACCESS_KEY=myaccesskey
AWS_SECRET_ACCESS_KEY=mysecretkey
OTHER_VARIABLE=something

Use a package to load these variables automatically.

If you look at the stub script in {{ cookiecutter.module_name }}/data/make_dataset.py, it uses a package called python-dotenv to load up all the entries in this file as environment variables so they are accessible with os.environ.get. Here's an example snippet adapted from the python-dotenv documentation:

python
# {{ cookiecutter.module_name }}/data/dotenv_example.py
import os
from dotenv import load_dotenv, find_dotenv

# find .env automagically by walking up directories until it's found
dotenv_path = find_dotenv()

# load up the entries as environment variables
load_dotenv(dotenv_path)

database_url = os.environ.get("DATABASE_URL")
other_variable = os.environ.get("OTHER_VARIABLE")

AWS CLI configuration

When using Amazon S3 to store data, a simple method of managing AWS access is to set your access keys to environment variables. However, managing mutiple sets of keys on a single machine (e.g. when working on multiple projects) it is best to use a credentials file, typically located in ~/.aws/credentials. A typical file might look like:

text
[default]
aws_access_key_id=myaccesskey
aws_secret_access_key=mysecretkey

[another_project]
aws_access_key_id=myprojectaccesskey
aws_secret_access_key=myprojectsecretkey

You can add the profile name when initialising a project; assuming no applicable environment variables are set, the profile credentials will be used be default.

Encourage adaptation from a consistent default

To keep this structure broadly applicable for many different kinds of projects, we think the best approach is to be liberal in changing the folders around for your project, but be conservative in modifying the default cookiecutter structure for all projects.

We've created a folder-layout label specifically for issues proposing to add, subtract, rename, or move folders around. More generally, we've also created a needs-discussion label for issues that should have some careful discussion and broad support before being implemented.

Examples of template adaptation and evolution

A project's organizational needs may differ from the start and can change over time. Here are some examples of directions to go in evolving your project structure.

Example 1: Simplifying

Some projects don't require multiple sub-directories to organize their module code. When a few python files can effectively accomplish all that is required, flattening folders into files can make things easier to track and maintain. You can see an example of this in our cyfi package. If it's in the template but you don't need it, delete it!

Example 2: Expanding

By contrast, we've added more folders to organize module code on more complex projects. A good example of this is our zamba package for which we've introduced new folders to handle task-specific portions of the codebase.

Example 3: Re-organizing

On long-running projects, the notebooks folder can get congested. One adaptation we've employed is to add a top-level research/ folder (and a corresponding data/research data folder) that contains sub-folders for individual experiments. These sub-folders can contain their own notebooks, code, and even their own Makefiles that inherit from the parent project Makefile.


Project structure and reproducibility is talked about more in the R research community. Here are some projects and blog posts if you're working in R that may help you out.

Finally, a huge thanks to the Cookiecutter project (github), which is helping us all spend less time thinking about and writing boilerplate and more time getting things done.


Docs Using The Template (`docs/docs/using-the-template.md`)

Using the template

You've created your project. You've read the opinions section. You're ready to start doing some work.

Here's a quick guide of the kinds of things we do once our project is ready to go. We'll walk through this example using git and GitHub for version control and jupyter notebooks for exploration, but you can use whatever tools you like.

Set up version control

Often, we start by initializing a git repository to track the code we write in version control and collaborate with teammates. At the command line, you can do this with the following commands which do the following: turn the folder into a git repository, add all of the files and folders created by CCDS into source control (except for what is in the .gitignore file), and then make a commit to the repository.

bash
# From inside your newly created project directory
git init
git add .
git commit -m "CCDS defaults"

We usually commit the entire default CCDS structure so it is easy to track the changes we make to the structure in version history.

Now that the default layout is committed, you should push it to a shared repository. You can do this through the interface of whatever source control platform you use. This may be GitHub, GitLab, Bitbucket, or something else.

If you use GitHub and have the gh cli tool you can easily create a new repository for the project from the commandline.

bash
gh repo create

You'll be asked a series of questions to set up the repository on GitHub. Once you're done you'll be able to push the changes in your local repository to GitHub.

Make as a task runner

GNU Make is a tool that is typically pre-installed on Linux and macOS systems, and we use it as a "task runner" for CCDS projects. This means that when we have a series of shell commands we might want to run, such setting up a virtual environment or syncing the data to cloud storage, we set them up as recipes in the Makefile. To use a recipe, simply call

bash
make RECIPE_NAME

where RECIPE_NAME is the name of a recipe like requirements or sync_data_up. Projects created by CCDS include a Makefile with several recipes we've predefined. You'll see them referenced in the sections below. To see a list of all available commands, just call

bash
make

on its own.

!!! note "Using Windows?"

text
If you are using Windows, you may need to install Make. See the ["Installing Make on Windows"](#installing-make-on-windows) section below.

Create a Python virtual environment

We often use Python for our data science projects. We use a virtual environment to manage the packages we use in our project. This is a way to keep the packages we use in our project separate from the packages we use in other projects. This is especially important when we are working on multiple projects at the same time.

Cookicutter Data Science supports a few options for Python virtual environment management, but no matter which you choose, you can create an environment with the following commands:

bash
make create_environment

Once the environment is created, you'll want to make sure to activate it. You'll have to do this following the instructions for your specific environment manager. We recommend using a shell prompt that shows you which environment you are in, so you can easily tell if you are in the right environment, for example starship. You can also use the command which python to make sure that your shell is pointing to the version of Python associated with your virtual environment.

Once you are sure that your environment is activated in your shell, you can install the packages you need for your project. You can do this with the following command:

bash
make requirements

Add your data

There's no universal advice for how to manage your data, but here are some recommendations for starting points depending on where the data comes from:

  • Flat files (e.g., CSVs or spreadsheets) that are static - Put these files into your data/raw folder and then run make sync_data_up to push the raw data to your cloud provider.
  • Flat files that change and are extracted from somewhere - Add a Python script to your source module in data/make_dataset.py that downloads the data and puts it in the data/raw folder. Then you can use this to get the latest and push it up to your cloud host as it changes (be careful not to override your raw data).
  • Databases you connect to with credentials - Store your credentials in .env. We recommend adding a db.py file or similar to your data module that connects to the database and pulls data. If your queries generally fit into memory, you can just have functions in the db.py to load data that you use in analysis. If not, you'll want to add a script like above to download the data to the data/raw folder.

Check out a branch

We'll talk about code review later, but it's a good practice to use feature branches and pull requests to keep your development organized. Now that you have source control configured, you can check out a branch to work with:

text
git checkout -b initial-exploration

Open a notebook

!!! note

text
The following assumes you're using a Jupyter notebook, but while the specific commands for another notebook tool may look a little bit different, the process guidance still applies.

Now you're ready to do some analysis! Make sure that your project-specific environment is activated (you can check with which jupyter) and run jupyter notebook notebooks to open a Jupyter notebook in the notebooks/ folder. You can start by creating a new notebook and doing some exploratory data analysis. We often name notebooks with a scheme that looks like this:

text
0.01-pjb-data-source-1.ipynb
  • 0.01 - Helps keep work in chronological order. The structure is PHASE.NOTEBOOK. NOTEBOOK is just the Nth notebook in that phase to be created. For phases of the project, we generally use a scheme like the following, but you are welcome to design your own conventions:
    • 0 - Data exploration - often just for exploratory work
    • 1 - Data cleaning and feature creation - often writes data to data/processed or data/interim
    • 2 - Visualizations - often writes publication-ready viz to reports
    • 3 - Modeling - training machine learning models
    • 4 - Publication - Notebooks that get turned directly into reports
  • pjb - Your initials; this is helpful for knowing who created the notebook and prevents collisions from people working in the same notebook.
  • data-source-1 - A description of what the notebook covers

Now that you have your notebook going, start your analysis!

Refactoring code into shared modules

As your project goes on, you'll want to refactor your code in a way that makes it easy to share between notebooks and scripts. We recommend creating a module in the {{ cookiecutter.module_name }} folder that contains the code you use in your project. This is a good way to make sure that you can use the same code in multiple places without having to copy and paste it.

Because the default structure is a Python package and is installed by default, you can do the following to make that code available to you within a Jupyter notebook.

First, we recommend turning on the autoreload extension. This will make Jupyter always go back to the source code for the module rather than caching it in memory. If your notebook isn't reflecting the latest changes from your changes to a .py file, try restarting the kernel and make sure autoreload is on. We add a cell at the top of the notebook with the following:

text
%load_ext autoreload
%autoreload 2

Now all your code should be importable. At the start of the CCDS project, you picked a module name. It's the same name as the folder that is in the root project directory. For example, if the module name were my_project you could use code by importing it like:

python
from my_project.data import make_dataset

data = make_dataset()

Now it should be easy to do any refactoring you need to do to make your code more modular and reusable.

Make your code reviewable

We try to review every line of code written at DrivenData. Data science code in particular has the risk of executing without erroring, but not being "correct" (for example, you use standard deviation in a calculation rather than variance). We've found the best way to catch these kinds of mistakes is a second set of eyes looking at the code.

Right now on GitHub, it is hard to observe and comment on changes that happen in Jupyter notebooks. We develop and maintain a tool called nbautoexport that automatically exports a .py version of your Jupyter notebook every time you save it. This means that you can commit both the .ipynb and the .py to source control so that reviewers can leave line-by-line comments on your notebook code. To use it, you will need to add nbautoexport to your requirements file and then run make requirements to install it.

Once nbautoexport is installed, you can setup the nbautoexport tool for your project with the following commands at the commandline:

text
nbautoexport install
nbautoexport configure notebooks

Once you're done with your work, you'll want to add it to a commit and push it to GitHub so you can open a pull request. You can do that with the following commandline commands

text
git add .  # stage all changed files to include them in the commit
git commit -m "Initial exploration"  # commit the changes with a message
git push  # publish the changes

Now you'll be able to create a Pull Request in GitHub.

Changing the `Makefile`

There's no magic in the Makefile. We often add project-specific commands or update the existing ones over the course of a project. For example, we've added scripts to generate reports with pandoc, build and serve documentation, publish static sites from assets, package code for distribution, and more.

Installing Make on Windows

Unfortunately, GNU Make is not typically pre-installed on Windows. Here are a few different options for getting Make:

  • Use a package manager. You will need to install the package manager first if you don't already have it.
  • Windows Subsystem for Linux. WSL is a full, non-virtualized Linux environment inside Windows. You can use it to run all of your data science workflows on Ubuntu, and it will have Make included. See instructions for installing WSL here.
  • Cygwin. A Unix-like development environment that includes Make. See instructions about installing Cygwin here.
  • MinGW. A GNU development environment that runs on Windows and includes Make. See information about installing MinGW here.

Docs V1 (`docs/docs/v1.md`)

Template v1

While v1 has been deprecated and we recommend using v2 moving forward, you can still use the v1 template should you so choose. Below you'll find there requirements and default folder structure for the v1 template.

Requirements

Starting a new project

Starting a new project is as easy as running this command at the command line. No need to create a directory first, the cookiecutter will do it for you.

nohighlight
cookiecutter https://github.com/drivendataorg/cookiecutter-data-science

Example

Directory structure

text
/* Detailed source-code truncated for AI context efficiency. */

Docs Why (`docs/docs/why.md`)

Why use this project structure?

We're not talking about bikeshedding the indentation aesthetics or pedantic formatting standards โ€” ultimately, data science code quality is about correctness and reproducibility.

When we think about data analysis, we often think just about the resulting reports, insights, or visualizations. While these end products are generally the main event, it's easy to focus on making the products look nice and ignore the quality of the code that generates them. Because these end products are created programmatically, code quality is still important! And we're not talking about bikeshedding the indentation aesthetics or pedantic formatting standards โ€” ultimately, data science code quality is about correctness and reproducibility.

It's no secret that good analyses are often the result of very scattershot and serendipitous explorations. Tentative experiments and rapidly testing approaches that might not work out are all part of the process for getting to the good stuff, and there is no magic bullet to turn data exploration into a simple, linear progression.

That being said, once started it is not a process that lends itself to thinking carefully about the structure of your code or project layout, so it's best to start with a clean, logical structure and stick to it throughout. We think it's a pretty big win all around to use a fairly standardized setup like this one. Here's why:

Other people will thank you

Nobody sits around before creating a new Rails project to figure out where they want to put their views; they just run rails new to get a standard project skeleton like everybody else.

A well-defined, standard project structure means that a newcomer can begin to understand an analysis without digging in to extensive documentation. It also means that they don't necessarily have to read 100% of the code before knowing where to look for very specific things.

Well organized code tends to be self-documenting in that the organization itself provides context for your code without much overhead. People will thank you for this because they can:

  • Collaborate more easily with you on this analysis
  • Learn from your analysis about the process and the domain
  • Feel confident in the conclusions at which the analysis arrives

A good example of this can be found in any of the major web development frameworks like Django or Ruby on Rails. Nobody sits around before creating a new Rails project to figure out where they want to put their views; they just run rails new to get a standard project skeleton like everybody else. Because that default project structure is logical and reasonably standard across most projects, it is much easier for somebody who has never seen a particular project to figure out where they would find the various moving parts.

Another great example is the Filesystem Hierarchy Standard for Unix-like systems. The /etc directory has a very specific purpose, as does the /tmp folder, and everybody (more or less) agrees to honor that social contract. That means a Red Hat user and an Ubuntu user both know roughly where to look for certain types of files, even when using each other's system โ€” or any other standards-compliant system for that matter!

Ideally, that's how it should be when a colleague opens up your data science project.

You will thank you

Ever tried to reproduce an analysis that you did a few months ago or even a few years ago? You may have written the code, but it's now impossible to decipher whether you should use make_figures.py.old, make_figures_working.py or new_make_figures01.py to get things done. Here are some questions we've learned to ask with a sense of existential dread:

  • Are we supposed to go in and join the column X to the data before we get started or did that come from one of the notebooks?
  • Come to think of it, which notebook do we have to run first before running the plotting code: was it "process data" or "clean data"?
  • Where did the shapefiles get downloaded from for the geographic plots?
  • Et cetera, times infinity.

These types of questions are painful and are symptoms of a disorganized project. A good project structure encourages practices that make it easier to come back to old work, for example separation of concerns, abstracting analysis as a DAG, and engineering best practices like version control.

Nothing here is binding

"A foolish consistency is the hobgoblin of little minds" โ€” Ralph Waldo Emerson (and PEP 8!)

Disagree with a couple of the default folder names? Working on a project that's a little nonstandard and doesn't exactly fit with the current structure? Prefer to use a different package than one of the (few) defaults?

Go for it! This is a lightweight structure, and is intended to be a good starting point for many projects. Or, as PEP 8 put it:

Consistency within a project is more important. Consistency within one module or function is the most important. ... However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!


{{ Cookiecutter.Repo Name }} Docs Mkdocs Mkdocs.Yml (`{{ cookiecutter.repo_name }}/docs/mkdocs/mkdocs.yml`)

site_name: {{ cookiecutter.project_name }}

{% if cookiecutter.author_name %}

site_author: {{ cookiecutter.author_name }}

{% endif %}


--- METRICS ---