Pulse Data Hub

Git and GitHub for Data Science: A Hands-On Guide with a Real Project

Most data science projects start as a folder of notebooks called things like analysis_final_v3_REAL.ipynb. Git fixes that. It records every version of your code, lets you try an idea on a branch without breaking what works, and lets you undo a mistake from last week. GitHub puts that history online, so you can back it up, share it with a team and show it to employers.

This guide sets up a real data science project from scratch: a customer churn analysis with a dataset, a notebook, Python code and tests. Every command was run before publishing, and every output shown is what Git printed. It also covers the parts general Git tutorials skip: what to do with data files, why notebooks make messy diffs and how to fix that, and how to undo the classic mistake of committing a dataset or a password.

Git and GitHub: what’s the difference?

  • Git is a program on your computer that tracks changes to files. It works offline and stores the full history in a hidden .git folder inside your project.
  • GitHub is a website that hosts Git projects (repositories). It adds backups, sharing, pull requests for reviewing changes, issue tracking and automation with GitHub Actions. GitLab and Bitbucket do the same job.

You use Git commands to save versions locally, then push them to GitHub.

Diagram of the Git workflow: files move from the working folder to the staging area with git add, into the local repository with git commit, and up to GitHub with git push; git pull brings changes back down
Where your files go: git add stages changes, git commit saves them locally and git push sends them to GitHub.

What belongs in Git, and what doesn’t

Git is built for text files you edit by hand. Data science projects also produce large and generated files, and those cause most of the problems beginners hit.

Put in GitKeep out of Git
Python code and scriptsRaw and processed data files
Notebooks, with outputs stripped (see below)Trained model files (.pkl, .joblib, .keras)
requirements.txt or environment.ymlPasswords, API keys and .env files
Tests, configuration and the READMEVirtual environments and __pycache__ folders
A short note on where the data comes fromLarge generated outputs such as plots and reports

There are hard limits too. GitHub warns about files over 50 MiB and blocks files larger than 100 MiB, and the web uploader stops at 25 MiB. A repository full of CSV files also becomes slow to clone, because Git keeps every version of every file forever.

Step 1: Install and set up Git

Download Git from git-scm.com (on Windows, Git for Windows) or install it with your package manager, then check it works. Any recent version is fine; these examples need 2.23 or later for git switch.

git --version

Output:

git version 2.43.0

Tell Git who you are. Your name and email are attached to every commit, so use the email address of your GitHub account. The last line names the first branch main, which is what GitHub uses.

git config --global user.name "Ana Silva"
git config --global user.email "ana@example.com"
git config --global init.defaultBranch main
git config --global --list

Output:

user.name=Ana Silva
user.email=ana@example.com
init.defaultbranch=main

Create a free account at github.com if you don’t have one. Free accounts include unlimited public and private repositories.

Step 2: Create a project and start tracking it

A predictable folder layout makes a project easy to navigate, for you in six months and for anyone you share it with:

churn-analysis/
├── data/
│   ├── README.md          # where the data comes from
│   └── raw/customers.csv  # the dataset (not tracked by Git)
├── models/                # trained models (not tracked)
├── notebooks/             # exploration
├── src/                   # reusable code: features, training
├── tests/
├── .env                   # secrets (not tracked)
├── README.md
└── requirements.txt

Turn the folder into a Git repository with git init, then ask Git what it sees:

cd churn-analysis
git init
git status

Output:

Initialized empty Git repository in /home/you/churn-analysis/.git/

On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	.env
	README.md
	data/
	models/
	requirements.txt
	src/
	tests/

nothing added to commit but untracked files present (use "git add" to track)

Git has found everything, including the 5,000-row dataset, the trained model and the .env file with an API key in it. If you ran git add . now, all of it would be saved in the history and, once pushed, on GitHub. So the next step comes first.

Step 3: Write a .gitignore before your first commit

A .gitignore file lists files and folders Git should never track. Create it in the project root:

# Data and models: keep them out of Git
data/*
!data/README.md
models/
*.pkl
*.joblib

# Secrets
.env

# Python and Jupyter clutter
__pycache__/
.ipynb_checkpoints/
.venv/

data/* ignores everything inside data/, and !data/README.md makes one exception, so the note explaining where the data comes from is still saved:

# Data

raw/customers.csv: export from the billing system, 5,000 customers, Oct 2026.
Not stored in Git. Ask the data team for access.

Check again:

git status

Output:

On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	.gitignore
	README.md
	data/
	requirements.txt
	src/
	tests/

nothing added to commit but untracked files present (use "git add" to track)

.env and models/ have gone, and data/ is still listed only because of its README. GitHub’s github/gitignore repository has a ready-made Python template you can start from.

Step 4: Make your first commit

Saving a version takes two commands. git add chooses which changes go into the next snapshot (the staging area) and git commit saves the snapshot with a message.

git add .
git status --short

Output:

A  .gitignore
A  README.md
A  data/README.md
A  requirements.txt
A  src/__init__.py
A  src/features.py
A  tests/test_features.py

Only the files you want. Commit them:

git commit -m "Set up project structure, features and tests"
git log --oneline

Output:

[main (root-commit) 1f832e6] Set up project structure, features and tests
 7 files changed, 42 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 README.md
 create mode 100644 data/README.md
 create mode 100644 requirements.txt
 create mode 100644 src/__init__.py
 create mode 100644 src/features.py
 create mode 100644 tests/test_features.py

1f832e6 Set up project structure, features and tests

1f832e6 is the start of the commit’s ID; yours will be different. Write messages that say what changed and why, such as “Add tenure feature” or “Fix leakage in train/test split”. “Update” and “stuff” won’t help you later.

Step 5: Put the project on GitHub

On github.com, click New repository, name it churn-analysis, choose public or private, and leave “Add a README” unticked, because the project already has one. GitHub then shows the address of the empty repository. Connect your local project to it and push:

git remote add origin https://github.com/YOUR-USERNAME/churn-analysis.git
git branch -M main
git push -u origin main

origin is the conventional name for your main remote, and -u links your local main branch to it, so from now on git push and git pull need no extra arguments. Refresh the page on GitHub and your files and commit are there.

GitHub doesn’t accept your account password for Git commands. The easiest way to sign in is the GitHub CLI: install it, run gh auth login and follow the prompts. Git for Windows also includes Git Credential Manager, which opens a browser sign-in the first time you push. The alternative is an SSH key, which GitHub’s documentation walks through.

Step 6: Try an idea on a branch

Branches are where Git pays off for data science. Every experiment, a new model, a different feature or a risky refactor, can live on its own branch while main keeps working. If the idea fails, you delete the branch; if it works, you merge it.

git switch -c try-random-forest

Output:

Switched to a new branch 'try-random-forest'

Add a training script, src/train.py:

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

from src.features import add_features

df = add_features(pd.read_csv("data/raw/customers.csv"))
X = df[["tenure_years", "monthly_charges", "support_calls", "high_support"]]
y = df["churned"]

model = RandomForestClassifier(n_estimators=200, min_samples_leaf=20, random_state=0)
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print(f"Random forest ROC AUC: {scores.mean():.3f}")
python -m src.train

Output:

Random forest ROC AUC: 0.707

Commit the experiment on the branch, and put the result in the message so the history doubles as a lab notebook:

git add src/train.py
git commit -m "Add random forest baseline (ROC AUC 0.71)"

Output:

[try-random-forest e9d963b] Add random forest baseline (ROC AUC 0.71)
 1 file changed, 13 insertions(+)
 create mode 100644 src/train.py

Switch back to main and the file disappears, because it only exists on the branch. When you’re happy with the experiment, merge it in and delete the branch:

git switch main
git merge try-random-forest
git branch -d try-random-forest

Output:

Switched to branch 'main'
Updating 1f832e6..e9d963b
Fast-forward
 src/train.py | 13 +++++++++++++
 1 file changed, 13 insertions(+)
 create mode 100644 src/train.py
Deleted branch try-random-forest (was e9d963b).

Working with a team: pull requests

On a team, you don’t merge your own branch locally. Push it instead with git push -u origin try-random-forest, and GitHub offers to open a pull request. A pull request shows the changes line by line, lets teammates comment and suggest edits, runs your automated tests, and merges the branch on GitHub when it’s approved. Run git pull afterwards to bring the merged main back to your computer.

Step 7: See exactly what changed

Before committing, git diff shows your uncommitted changes line by line. Here a new feature has been added to src/features.py:

git diff

Output:

diff --git a/src/features.py b/src/features.py
index 1fc34e4..fb5f610 100644
--- a/src/features.py
+++ b/src/features.py
@@ -5,4 +5,5 @@ def add_features(df: pd.DataFrame) -> pd.DataFrame:
     out = df.copy()
     out["tenure_years"] = out["tenure_months"] / 12
     out["high_support"] = (out["support_calls"] >= 3).astype(int)
+    out["new_customer"] = (out["tenure_months"] < 6).astype(int)
     return out

Lines starting with + were added and lines with - were removed. git commit -am "message" stages and commits changes to files Git already tracks in one step.

git commit -am "Add new_customer feature"

Output:

[main 8220afe] Add new_customer feature
 1 file changed, 1 insertion(+)

Jupyter notebooks in Git: strip the outputs

A notebook is a JSON file that stores your code and its outputs: tables, printed text and every chart as a long block of encoded image data. That makes notebook diffs huge and unreadable, and merging two people’s changes to the same notebook is painful.

We measured it with the project’s exploration notebook, which has a summary table and two charts. Saved with outputs, the file is 36.7 KB; the code alone is 1.3 KB. Then we changed one number, the histogram’s bins=20 to bins=24, and re-ran the notebook:

Without nbstripoutWith nbstripout
Size of the change Git records35.3 KB0.4 KB
What the diff shows1 changed code line plus a redrawn chart as a 34 KB line of encoded image dataJust bins=20 → bins=24
Changing one number in a notebook with two charts, then re-running it.

The fix is the nbstripout tool, which removes outputs as files are committed while leaving them in your working copy, so you still see your charts:

pip install nbstripout
nbstripout --install
git add --renormalize .

nbstripout --install sets this up for the current repository only, so run it once in each project and ask teammates to do the same. git add --renormalize . applies it to notebooks that are already tracked. If you want readers on GitHub to see results without running the notebook, save key charts as image files in the README, or commit a separate rendered copy (HTML) of the notebooks you want to show.

Two other good habits: move code you reuse into .py files in src/, where Git diffs and tests work well, and keep notebooks for exploration and storytelling. Jupytext, which saves a plain-text copy of each notebook, is another option if you want readable diffs and outputs.

What to do with large data files

  • Keep data out and document it. The simplest approach, used above: ignore the data folder and write down where the data comes from and how to get it.
  • Git LFS (Large File Storage) stores large files outside the normal history and keeps a small pointer in Git. It’s built into GitHub but has storage and bandwidth quotas, so check your plan’s limits before relying on it.
  • DVC (Data Version Control) versions datasets and models in cloud storage such as S3, Google Cloud Storage or Azure, while Git tracks small files describing each version. It’s the usual choice when you need to reproduce exactly which data trained which model.

Fix common mistakes

You committed a data file

git rm --cached stops tracking a file without deleting it from your computer:

git rm --cached data/raw/customers.csv
git commit -m "Stop tracking raw data"

Output:

rm 'data/raw/customers.csv'
[main c2c2564] Stop tracking raw data
 1 file changed, 5001 deletions(-)
 delete mode 100644 data/raw/customers.csv

The file is still on your disk and no longer tracked. But it remains in the earlier commit, and therefore on GitHub if you pushed it. If the data is private, remove it from the whole history with the git filter-repo tool, or delete and recreate the repository if nobody else uses it yet.

You committed a password or API key

Treat it as stolen: revoke or rotate the key at the provider immediately, because bots scan public repositories for keys within minutes. Then remove it from the history as above and move it into .env. GitHub’s push protection blocks many common key formats before they reach a public repository, but don’t rely on it.

You want to undo a commit you already pushed

git revert creates a new commit that undoes an old one, without rewriting history, so it’s safe on shared branches:

git revert 8220afe

Output:

[main f619d96] Revert "Add new_customer feature"
 Date: Wed Nov 4 15:41:33 2026 +0600
 1 file changed, 1 deletion(-)

Quick fixes

ProblemCommand
Throw away uncommitted changes to a filegit restore src/features.py
Unstage a file you added by mistakegit restore --staged notes.txt
Fix the message of your last commit (not yet pushed)git commit --amend -m "Better message"
See who changed each line of a file and whengit blame src/features.py
Go back to look at an old versiongit switch --detach 1f832e6, then git switch main

Run your tests automatically with GitHub Actions

GitHub Actions can run your tests every time someone pushes or opens a pull request, so a broken feature function is caught before it reaches main. Save this file as .github/workflows/tests.yml:

name: tests

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt
      - run: python -m pytest -q

On every push to main and every pull request, GitHub starts a fresh Linux machine, checks out the code, installs Python 3.13 and the pinned packages, and runs the tests. We ran the same steps in a clean environment and got 1 passed. Results appear on the Actions tab and as a green tick or red cross on each pull request. Public repositories get Actions for free; private repositories get a monthly allowance of free minutes.

The test it runs is small but real:

import pandas as pd

from src.features import add_features


def test_add_features():
    df = pd.DataFrame({"tenure_months": [24], "support_calls": [4]})
    out = add_features(df)
    assert out.loc[0, "tenure_years"] == 2
    assert out.loc[0, "high_support"] == 1

Make your repository portfolio-ready

For many hiring managers, your GitHub profile is your data science portfolio. A few projects that are easy to understand beat many half-finished ones.

  • Write a README that answers the obvious questions: what problem the project solves, what data it uses, the approach, the key result with a chart, and how to run it.
  • Make it reproducible. Pin versions in requirements.txt, say where to get the data, and set random seeds.
  • Show results honestly, including what didn’t work. A model that beats a simple baseline is more convincing than a suspiciously perfect score.
  • Pin your best repositories to your profile, and add a profile README (a repository named after your username) with a short introduction.
  • Add a license if you want others to reuse your code; MIT is a common choice.

Does GitHub Copilot help with data science?

GitHub Copilot suggests code as you type in VS Code (including Jupyter notebooks), JetBrains IDEs and other editors, and its chat can explain or write code. It’s good at the repetitive parts of data science: pandas reshaping, plotting boilerplate, scikit-learn pipelines and test cases. It can also be confidently wrong, for example by leaking test data into preprocessing or picking the wrong metric, so read every suggestion and keep your tests. There’s a free plan with monthly limits, and verified students and teachers can get the paid plan free through GitHub Education.

Git commands cheat sheet

CommandWhat it does
git initStart tracking a folder
git statusShow what’s changed and what’s staged
git add <file> / git add .Stage changes for the next commit
git commit -m "message"Save a snapshot
git log --onelineList commits
git diffShow uncommitted changes
git switch -c <branch>Create a branch and switch to it
git merge <branch>Merge a branch into the current one
git push / git pullSend commits to GitHub / bring others’ commits down
git clone <url>Download a repository from GitHub
git revert <commit>Undo a commit with a new commit

Related tutorials

For more depth, the free Pro Git book covers Git itself, and the GitHub Actions documentation covers workflows.

FAQ

Do data scientists need to know Git?

Yes. Almost every data science team keeps its code in Git, usually on GitHub or GitLab, and job descriptions routinely list it. You don’t need advanced Git: add, commit, push, pull, branches and pull requests cover most daily work.

Should I put my dataset on GitHub?

Usually not. Keep raw data out with .gitignore and document where it comes from. Small public sample datasets (a few megabytes) are fine. For large or versioned data, use Git LFS or DVC, and never commit personal or confidential data to a public repository.

Can GitHub display Jupyter notebooks?

Yes. GitHub renders .ipynb files with their outputs, so a notebook committed with outputs looks like a report. If you strip outputs to keep diffs clean, show key results in the README or publish a rendered copy.

Is GitHub free?

Yes for most individual use: free accounts include unlimited public and private repositories, plus GitHub Actions minutes and Git LFS storage within monthly limits. Paid plans add more minutes, storage and team features.

What’s the difference between git pull and git fetch?

git fetch downloads new commits from GitHub without changing your files. git pull fetches and then merges them into your current branch.

Git LFS or DVC for data?

Git LFS is simpler and built into GitHub, but has storage and bandwidth quotas. DVC stores data in your own cloud storage and tracks which data produced which model, which matters for reproducible machine learning. For a portfolio project, documenting where to download the data is usually enough.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights