Setting Up a Virtual Environment for Jupyter Notebook (Windows 11 tutorial)
Last update: January 29, 2025
Using virtual environments in Jupyter Notebook ensures a clean and manageable workspace for Python projects. Here’s a step-by-step guide to setting up a virtual environment and using it in Jupyter.
Step 1: Open Terminal as Administrator
To begin, open the terminal with administrative privileges:
- Right-click on the Windows Start menu.
- Select Terminal (Admin).
Step 2: Modify Execution Policy
In the admin terminal, run the following command to allow scripts to be executed:
set-executionpolicy unrestricted
After running the command, you can close the admin terminal.
Step 3: Create a Folder for Your Jupyter Notebook
Navigate to a desired location and create a dedicated folder for your project.
Step 4: Open Terminal in the Project Folder
- Right-click inside the folder.
- Choose Open in Terminal.
Step 5: Create and Activate a Virtual Environment
Run the following command to create a virtual environment in your folder:
python -m venv .venv
Activate the virtual environment:
.venv\scripts\activate
Step 6: Install Jupyter
With the virtual environment activated, install Jupyter Notebook and the necessary kernel package:
pip install jupyter ipykernel
Step 7: Install Additional Packages
If your project requires additional packages, install them as needed. For example, to install NumPy:
pip install numpy
Step 8: Register the Virtual Environment in Jupyter
Run the following command to add the virtual environment to Jupyter:
python -m ipykernel install --user --name=.venv --display-name "example-env"
Step 9: Launch Jupyter Notebook
Start Jupyter Notebook with:
jupyter notebook
Step 10: Select the Virtual Environment in Jupyter
- Click New.
- Select example-env from the available kernel options.
Step 11: Verify the Setup
Inside a new notebook, run the following Python code to ensure the environment is working:
import numpy as np
a = np.array([3, 5, 7])
a
If you see the expected output, your setup is complete!
By following these steps, you ensure that your Jupyter notebooks run in an isolated environment, keeping dependencies well-organized and avoiding conflicts with system-wide installations.