A working Python environment and basic Python programming knowledge remove a common beginner obstacle: not knowing whether a problem comes from the data, the code, or the installation. This guide sets up a small project, loads a CSV file, and helps you complete your first analysis so you can run it again later.

Choose a Simple Python Setup for Your First Data Analysis

A first project needs four pieces:

  • Python runs your analysis code.
  • pip installs packages such as pandas and Matplotlib.
  • A virtual environment keeps this project’s packages separate from those used by other Python projects.
  • JupyterLab provides a notebook for keeping code, results, and notes together.

The recommended beginner path uses the standard Python installer, a venv virtual environment, and JupyterLab. This setup is simple, widely supported, and makes each component’s role clear. Conda distributions and code editors with notebook support are also valid options, but choose one path for now. Mixing package managers early on can make it difficult to tell which tool installed or controls a package.

This project uses a small, illustrative sales dataset. You will load it, inspect its structure, calculate revenue by category, create a chart, and save the result.

Keep the project in one folder:

first-analysis/
├── analysis.ipynb
├── data/
│   └── sales.csv
├── outputs/
├── requirements.txt
└── README.md

Real story

Real Story: I once opened JupyterLab to do a “quick analysis” and spent 40 minutes convincing my laptop that pandas existed. I finally got the notebook running, loaded the CSV, and felt triumphant until I realized I’d been plotting the column names instead of the data. The graph looked beautifully blank, which was honestly the most on-brand result possible.

Have a story of your own? Share it in the comments below.

Install Python and Create an Isolated Data Science Environment

  1. Install a current stable Python release supported by the main data tools. Choose the latest stable release rather than an alpha, beta, release candidate, or other prerelease. Before choosing a newly released version, confirm that pandas, Matplotlib, and JupyterLab support it. Download Python from the official Python website, or use an established Python distribution if your school or workplace already recommends one.

    After installation, open a new terminal and check that Python is available.

    On macOS or Linux:

    python3 --version
    

    On Windows:

    py --version
    

    Expected output: A version number beginning with Python, such as Python 3.x.x.

  2. Create the project folder and place a virtual environment inside it. Run these commands from a location where you keep projects.

    On macOS or Linux:

    mkdir first-analysis
    cd first-analysis
    mkdir data
    mkdir outputs
    python3 -m venv .venv
    source .venv/bin/activate
    

    On Windows PowerShell:

    mkdir first-analysis
    cd first-analysis
    mkdir data
    mkdir outputs
    py -m venv .venv
    .\.venv\Scripts\Activate.ps1
    

    Once activated, your terminal prompt usually shows (.venv) at the beginning.

    A virtual environment is an isolated Python installation for one project. Packages installed there stay there instead of changing the Python setup used by other projects on your computer.

  3. Install the packages needed for this analysis.

    python -m pip install --upgrade pip
    python -m pip install pandas matplotlib jupyterlab ipykernel
    

    Then register this environment as a named Jupyter kernel:

    python -m ipykernel install --user --name data-analysis --display-name "Python (data-analysis)"
    

    Expected output: The installation commands should finish without error messages. The kernel command should confirm that it installed a kernel specification.

    The pandas package handles tabular data. Matplotlib creates charts. JupyterLab runs notebooks, while ipykernel lets a notebook use this particular virtual environment.

Verify the Environment Before Writing Analysis Code

  1. Check that the active terminal is using the virtual environment rather than a system-wide Python installation.

    python -c "import sys; print(sys.executable)"
    

    Expected output: The displayed path should include first-analysis/.venv or a similar .venv folder.

  2. Start JupyterLab with the virtual environment active and the terminal in the first-analysis folder.

    python -m jupyter lab
    

    JupyterLab should open in your browser. Create a new notebook and select the kernel named Python (data-analysis).

  3. Run this verification cell in the notebook.

    import sys
    import matplotlib
    import pandas as pd
    
    print("Python:", sys.version.split()[0])
    print("pandas:", pd.__version__)
    print("Matplotlib:", matplotlib.__version__)
    print("Check:", 12 * 3)
    print("Environment is ready.")
    

    Expected output: You should see Python and package version numbers, followed by:

    Check: 36
    Environment is ready.
    

Troubleshooting

  • If python, python3, or py is “not found,” close and reopen the terminal after installing Python. On macOS or Linux, try python3 where a command uses python.
  • If ModuleNotFoundError appears for pandas or Matplotlib, activate .venv again and install packages with python -m pip install .... Using python -m pip helps ensure pip belongs to the same Python interpreter.
  • If the notebook cannot import a package that works in the terminal, it is probably using the wrong kernel. In JupyterLab, switch the notebook kernel to Python (data-analysis) and rerun the cell.
  • If PowerShell blocks environment activation, check your organization’s policy. You can also use Command Prompt, where activation uses .\.venv\Scripts\activate.bat.

Load and Inspect a Small Dataset Without Making Assumptions

  1. Create a file named sales.csv inside the data folder. Paste in this sample data and save it as plain CSV text.

    date,category,units,revenue
    2026-08-01,Books,3,45
    2026-08-01,Games,1,60
    2026-08-02,Books,2,30
    2026-08-02,Home,4,80
    2026-08-03,Games,2,120
    2026-08-03,Home,1,20
    2026-08-04,Books,1,15
    2026-08-04,Games,1,60
    

    Each row represents one sale record. These values are illustrative rather than drawn from a real store’s sales data. The revenue column uses illustrative revenue units; no currency is specified.

  2. In the notebook, load the CSV with a relative path. This keeps the project easier to move or share because the path does not depend on your computer’s folder names.

    from pathlib import Path
    
    import pandas as pd
    
    DATA_PATH = Path("data") / "sales.csv"
    
    sales = pd.read_csv(DATA_PATH)
    
    print(sales.head())
    print(f"\nRows, columns: {sales.shape}")
    
    print("\nData types:")
    print(sales.dtypes)
    
    print("\nMissing values:")
    print(sales.isna().sum())
    

    Expected output: The dataset should have eight rows and four columns.

    Rows, columns: (8, 4)
    

    The date column will initially appear as an object, meaning pandas read it as text. The missing-value check should report zero missing values for every column.

  3. Convert the columns to the types you expect, then validate the basic assumptions before calculating totals.

    required_columns = {"date", "category", "units", "revenue"}
    
    missing_columns = required_columns - set(sales.columns)
    if missing_columns:
        raise ValueError(f"Missing columns: {missing_columns}")
    
    sales["date"] = pd.to_datetime(sales["date"], errors="raise")
    sales["units"] = pd.to_numeric(sales["units"], errors="raise")
    sales["revenue"] = pd.to_numeric(sales["revenue"], errors="raise")
    
    if sales.isna().any().any():
        raise ValueError("Missing values found. Inspect them before continuing.")
    
    if (sales["units"] <= 0).any():
        raise ValueError("Units must be greater than zero.")
    
    if (sales["revenue"] < 0).any():
        raise ValueError("Revenue cannot be negative in this dataset.")
    
    print(sales.dtypes)
    

    Expected output: The date column should now have a datetime type, while units and revenue should be numeric.

    This dataset contains no missing values, so there is nothing to remove or replace. With real data, do not automatically convert missing revenue to zero. A blank value might mean “unknown,” “not recorded,” or something else entirely. The right choice depends on how the data was collected.

Answer One Practical Question With Summaries and a Chart

  1. Define a narrow question before writing the calculation:

    Which product category generated the most revenue in this sample?

    Grouping the rows by category and summing the revenue column answers this question.

  2. Build a summary table.

    summary = (
        sales.groupby("category", as_index=False)
        .agg(
            total_revenue=("revenue", "sum"),
            average_sale_value=("revenue", "mean"),
            total_units=("units", "sum"),
        )
        .sort_values("total_revenue", ascending=False)
    )
    
    summary["average_sale_value"] = summary["average_sale_value"].round(2)
    
    summary
    

    Expected output: Your table should show these results.

    category total_revenue average_sale_value total_units
    Games 240 80.0 4
    Home 100 50.0 5
    Books 90 30.0 6

    The code relies on three common pandas operations:

    • groupby() separates records into categories.
    • agg() calculates several summaries for each category.
    • sort_values() places the highest-revenue category first.
  3. Create a bar chart that presents the same result visually.

    import matplotlib.pyplot as plt
    
    OUTPUT_PATH = Path("outputs") / "revenue_by_category.png"
    OUTPUT_PATH.parent.mkdir(exist_ok=True)
    
    fig, ax = plt.subplots(figsize=(7, 4))
    
    bars = ax.bar(
        summary["category"],
        summary["total_revenue"],
        color="#4C78A8",
    )
    
    ax.set_title("Revenue by Product Category")
    ax.set_xlabel("Category")
    ax.set_ylabel("Revenue units")
    ax.bar_label(
        bars,
        labels=[f"{value:.0f}" for value in summary["total_revenue"]],
        padding=3,
    )
    
    fig.tight_layout()
    fig.savefig(OUTPUT_PATH, dpi=150, bbox_inches="tight")
    plt.show()
    

    Expected output: A bar chart should appear in the notebook, with Games as the tallest bar. A copy should also be saved at:

    outputs/revenue_by_category.png
    
  4. State the finding in plain language.

    In this sample, Games generated the most revenue, at 240 revenue units. Home sold more units than Games but generated less revenue. Within this small dataset, the categories therefore differ in revenue per sale.

    The result does not explain why Games produced more revenue. It does not prove that a category is more popular, more profitable, or better promoted. It describes only the records in this CSV.

Save the Analysis So Someone Else Can Reproduce It

Use this checklist before treating the project as complete:

  • Save the notebook as analysis.ipynb in the project’s top-level folder.

  • Keep the original CSV in data/sales.csv.

  • Keep generated charts in outputs/, separate from source data.

  • Record the installed package versions:

    python -m pip freeze > requirements.txt
    
  • Add .venv/ to a .gitignore file if you use version control. The environment can be recreated from requirements.txt; it does not need to be copied into the project.

  • Create a short README.md explaining the question, the data checks, and the main finding.

A minimal README might include this:

Question: Which category generated the most revenue?

Data checks:
- Parsed date values as dates.
- Confirmed there were no missing values.
- Confirmed units were positive and revenue was not negative.

Result:
Games had the highest total revenue in the sample, at 240 revenue units.

To recreate the environment:
1. Create and activate a virtual environment.
2. Run: python -m pip install -r requirements.txt
3. Run: python -m jupyter lab

For the next practice run, keep the project structure unchanged and alter one thing at a time. Try a second CSV, compare revenue by date instead of category, or improve the chart labels. Small, repeatable analyses build useful habits faster than a large project that cannot be rerun.