Set Up Python for Data Analysis
Step 1 in the Data Analysis with Python track: install Python, set up Jupyter Notebook, and prepare your environment for pandas, NumPy, and visualization libraries. Hands-on exercise included.
Focus: set up python for data analysis
So you've decided to learn data analysis with Python. You've likely heard amazing things about pandas, Jupyter Notebooks, and machine learning. But there's a frustrating catch: when you open a terminal, type import pandas, and hit Enter, you get a ModuleNotFoundError or, worse, you're running Python 2.7 from 2012. The internet gives you five different package managers, three different Python versions, and countless paths to a working conda environment. It's enough to make you want to go back to spreadsheets. This lesson will eliminate that frustration. You'll walk away with a clean, reproducible Python environment built specifically for data analysis — and you'll know exactly why every tool on your machine belongs there.
The problem this lesson solves
Data analysis without a proper environment is like trying to cook a complex meal in a kitchen with no counter space, mismatched pans, and a stove that only has two working burners. You might get something edible eventually, but it will take twice as long and feel messy.
Here's the pain developers face when they skip setup:
- Dependency hell: You install one package, and it breaks another. Your
numpyversion conflicts with yourmatplotlibversion, and suddenly your plots are blank. - System Python pollution: You blindly install packages into the system Python, and one day a critical OS tool stops working because you upgraded
python3-dev. - Version mismatch: You write code that works today, but a colleague (or a future you) runs it a month later on a different Python version, and everything explodes.
- No clear path: You end up with five Python installations, three
pipcommands, and no idea which one Jupyter is using. Your notebook says "kernel is dead," and you have no clue why.
Pro tip: Setting up your environment is not a one-time chore you should rush through. It's the foundation of every analysis you'll do. A good setup prevents hours of preventable debugging later.
Core concept / mental model
Think of your data analysis environment as a virtual kitchen. The base Python installation is your oven — it's essential, but you wouldn't cook everything on it directly. Your package manager (pip or conda) is your pantry, where you keep all your ingredients (libraries). Your virtual environment is a separate countertop where you organize a specific recipe's ingredients without cluttering the rest of your kitchen. Finally, Jupyter Notebook is your recipe book — it lets you combine the instructions (code), the results, and your notes in one living document.
In simple terms, you need four layers to set up Python for data analysis:
- Python interpreter: The language runtime. For data analysis, you want Python 3.10 or newer.
- Environment manager: Keep projects isolated so one project's library versions don't break another.
- Package installer: Download and install libraries (like pandas, numpy, matplotlib) into your environment.
- Interactive interface: Jupyter Notebook (or JupyterLab) for writing and running code cells, seeing outputs, and documenting your process.
Here's a visual analogy in words:
- System Python → the kitchen's main oven (don't touch it!)
- Virtual environment → your personal countertop (everything lives here)
- pip/conda → the pantry and shopping list
- Jupyter → the leather-bound recipe book you actually use
Once you internalize this layering, everything else in the track will feel more natural.
How it works step by step
Setting up your environment is a sequence of cause → effect actions. Here's the logical order:
- Install Python (or use a manager like
condathat bundles it) - Create a virtual environment to isolate your analysis workspace
- Install core libraries (NumPy, pandas, Matplotlib, Jupyter, and optionally Seaborn)
- Launch Jupyter and verify your installation with a quick import test
Step 1: Install Python
Make sure you have Python 3.10 or later. Check with:
python3 --version
If you're on Linux or macOS and don't have it, use your package manager (apt, brew). Windows users should download the official installer from python.org and check "Add Python to PATH" during installation — this is a common mistake.
Step 2: Create a virtual environment
A virtual environment is a self-contained folder with its own Python and package installations. This keeps your analysis projects clean and reproducible.
# Create a folder for our project
mkdir ~/data-analysis
cd ~/data-analysis
# Create a virtual environment
python3 -m venv .venv
# Activate it
source .venv/bin/activate # Linux/macOS
# .venv\Scripts\activate # Windows (command prompt)
# Your prompt should now show (.venv)
The name .venv is conventional, but you can name it anything.
Step 3: Install libraries
With the environment active, install the core data analysis stack using pip:
pip install --upgrade pip
pip install numpy pandas matplotlib jupyter seaborn
This installs the latest versions of:
- numpy: numerical operations and array computing
- pandas: data structures (like DataFrame) and data manipulation
- matplotlib: foundational plotting library
- jupyter: the notebook interface
- seaborn: statistical visualizations built on matplotlib (a bonus but worth having)
Step 4: Launch Jupyter and verify
jupyter notebook
Jupyter will open a web browser at http://localhost:8888 (or show a token in the terminal you can paste). Create a new notebook, and test your setup with:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
print("Python data analysis environment ready!")
print(f"NumPy version: {np.__version__}")
print(f"Pandas version: {pd.__version__}")
Expected output:
Python data analysis environment ready!
NumPy version: 1.26.4
Pandas version: 2.2.2
Pro tip: If you see any
ModuleNotFoundError, it means your Jupyter is running on a different Python than your environment. Checkimport sys; sys.executableto confirm your kernel is using the right interpreter.
Hands-on walkthrough
Let's go from zero to working environment in a single, complete example. You'll create a mini data analysis workflow to prove your setup is correct.
Step 1: Set up your project folder and environment
mkdir web-traffic-analysis
cd web-traffic-analysis
python3 -m venv .venv
source .venv/bin/activate # or .venv\Scripts\activate on Windows
Step 2: Install dependencies
pip install --upgrade pip
pip install numpy pandas matplotlib jupyter
This might take a couple of minutes, but you'll see each package download and install. No sudo, no system-wide changes.
Step 3: Launch Jupyter and create your first notebook
jupyter notebook
Create a new notebook named setup_test.ipynb and run the following cell:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Create a simple synthetic dataset
np.random.seed(42)
days = pd.date_range('2025-01-01', periods=30, freq='D')
page_views = np.random.randint(500, 2000, size=30)
df = pd.DataFrame({'date': days, 'page_views': page_views})
# Compute a quick stat
print(df['page_views'].describe())
# Create a line plot and save it
plt.figure(figsize=(10, 4))
plt.plot(df['date'], df['page_views'])
plt.title('Daily Page Views')
plt.xlabel('Date')
plt.ylabel('Views')
plt.tight_layout()
plt.savefig('page_views.png')
plt.show()
Expected output:
count 30.000000
mean 1199.800000
std 385.440327
min 610.000000
25% 937.500000
50% 1206.500000
75% 1471.250000
max 1893.000000
Name: page_views, dtype: float64
And you should see a line plot appear inside the notebook. If you see that, your environment is fully working!
Compare options / when to choose what
When it comes to setting up Python for data analysis, you have two main approaches: venv + pip and conda. Each has strengths, and the one you choose depends on your workflow.
| Feature | venv + pip | conda (Anaconda/Miniforge) |
|---|---|---|
| Base Python | System Python or Python.org installer | Bundled with conda (or use Miniforge) |
| Package management | Python packages (PyPI) | Python + non-Python libraries (e.g., CUDA, R) |
| Environment isolation | Yes, via venv |
Yes, via conda create |
| Popularity | Lightweight, standard for pure Python | Great for scientific stacks with complex dependencies |
| Learning curve | Low | Moderate (conda's own commands) |
| Best for | Quick, focused Python projects | Large scientific computing, mixed-language projects |
When to choose what:
- Use venv + pip for this tutorial if you want a minimal, standard setup. It's what most Python developers are familiar with, and it's fully sufficient for pandas, NumPy, Matplotlib, and Seaborn.
- Switch to conda if you need to manage libraries that aren't on PyPI (like certain geospatial tools) or if you want to avoid Python version conflicts entirely.
Another variation: Use Docker to package your environment in a container. This is excellent for reproducibility when you need to share an analysis with colleagues or deploy it to a server. However, for learning, a local venv is faster and more interactive.
Troubleshooting & edge cases
Even with a perfect guide, things can go wrong. Here are the most common issues you'll hit when setting up Python for data analysis, and how to fix them.
Error: command not found: python3 or python is not recognized
- Cause: Python isn't installed or not in your PATH.
- Fix: Install Python, and on Windows make sure you check
Add Python to PATHduring installation. On Linux/macOS, your package manager might usepython3instead ofpython.
Error: pip: command not found
- Cause: pip is not installed or not available in the environment.
- Fix: Inside your activated venv, run
python -m pip install --upgrade pip. That's the safest way to invoke pip.
Error: ModuleNotFoundError: No module named 'pandas' inside Jupyter
- Cause: Your Jupyter kernel is using a different Python than your venv.
- Fix: With your venv active, install
ipykerneland connect it:pip install ipykernelthenpython -m ipykernel install --user --name=myenv. After that, restart Jupyter and choose themyenvkernel from the menu.
Edge case: Using python vs python3
On many systems, python points to Python 2 or isn't defined. Always use python3 to create your venv unless you've verified python --version gives you 3.10+.
Edge case: Very old Python version
If your system Python is below 3.10, some data analysis libraries may not support it. Update to a recent stable version from python.org instead of fighting with old code.
Your environment is now robust. Embrace the command line, use virtual environments religiously, and you'll rarely face a 'works on my machine' problem.
What you learned & what's next
You've successfully set up Python for data analysis. Here's what you can now do:
- Explain the core idea behind a data analysis environment: Python interpreter + isolated virtual environment + package manager + interactive Jupyter interface.
- Complete the practical exercise of creating a venv, installing key libraries (numpy, pandas, matplotlib, jupyter), and running a notebook that imports them successfully.
- Verify your setup by running a simple pandas and plot example, which proves your packages are correctly installed and that your Jupyter kernel points to the right Python interpreter.
This foundation is step 1 of your data analysis journey. You now have the tools to move to the next lesson: handling data with pandas and NumPy. In that lesson, you'll load real datasets, clean them, and start exploring them — and you'll do it in the same notebook you've just mastered.
Your environment is clean, versioned, and ready. Now go make it work for you.
Practice recap
Create a new virtual environment and install pandas, numpy, and jupyter. Launch Jupyter, open a new notebook, and run the sample script to print a pandas DataFrame summary and generate a simple plot. If you see the dataframe output and a plot, your setup is solid. Next, save a requirements.txt file with pip freeze > requirements.txt to make your environment reproducible.
Common mistakes
- Installing packages into the system Python without a virtual environment, leading to dependency conflicts and a polluted system.
- Using
pip installinstead ofpython -m pip install, which can accidentally install to the wrong Python environment. - Forgetting to activate the virtual environment before running Jupyter, so the notebook kernel uses the global Python instead of your venv.
- Skipping the
--userflag when installing ipykernel, causing the kernel to not be found by Jupyter.
Variations
- Use conda/miniforge instead of venv + pip to manage Python versions and non-Python dependencies like CUDA.
- Use JupyterLab instead of the classic Jupyter Notebook for a more modern, extensible interface.
- Containerize your environment with Docker for reproducible data analysis across team members and servers.
Real-world use cases
- A data analyst at a startup needs to quickly prototype a churn analysis using pandas and matplotlib in a reproducible notebook.
- A university researcher sets up a shared environment for a Python workshop to ensure all students run the same library versions.
- A machine learning engineer creates an isolated venv per project to avoid conflicts between TensorFlow and PyTorch dependencies.
Key takeaways
- Always use a virtual environment to isolate your data analysis project and prevent dependency hell.
- Use
python -m pip installto avoid installing into the wrong Python environment. - Jupyter's kernel must point to the same Python interpreter as your venv or imports will fail.
- For pure Python stacks, venv + pip is lightweight and sufficient; switch to conda for complex scientific dependencies.
- Your environment setup is the foundation of every future analysis — take time to make it reproducible with a requirements.txt file.
- You can verify a clean setup in seconds with a simple pandas import and describe() test.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.