This a growing collection of small snippets of code that I use frequently, and otherwise would have been stored in my Gists on GitHub.


Setting up Jupyter Kernel for a Virtual Environment

# After activating virtual environment
pip install ipykernel
ipython kernel install --user --name="my-new-venv" --display-name="my-new-venv"

List and Uninstall Jupyter Kernel

jupyter kernelspec list

jupyter kernelspec uninstall XXXX


Removing Matplotlib figure transparency (in Jupyter Lab)

If you try to grab a figure directly from a Jupyter notebook without saving to a file first, the figure axis is transparent, which is not always desired.

fig = plt.gcf()

Temporarily change Seaborn plotting context with context manager

Seaborn has useful plotting context settings (talk, poster, paper, notebook) that you can permanently set for a session:


but you can also temporarily set a context for a particular plot that may differ than your other plots (talk vs paper)

with sns.plotting_context("paper"):
    sns.swarmplot(data=df, x="x", y="y")


Add column to dataframe and then return dataframe

You can add a new column to a dataframe (and set the values of the new column):

df["new_col"] = "A"

But if you need to return a dataframe (in chaining or list comprehension), you can use the .assign() method. The name of the new column is used as an argument with the method.

df = df.assign(new_col="A")


Start Git Repo with Empty Commit

This is useful in case you ever need to rebase your repo back to the beginning, because it’s bothersome to deal with a root commit.

git init
git commit --allow-empty -m "Initial commit"

Set Committer Date to Author Date

If you have to do a little rebasing but still want the comitter date to match the author date. This will apply to the last three commits.

git rebase --committer-date-is-author-date HEAD~3