Python for Data Analysis: Complete Beginner-to-Practical Guide

SS
Shajul Islam Sumon
November 04, 2026
  • 14 mins read
Laptop displaying a Python notebook with a summary table and a labelled chart.
In this article

A useful analysis starts with a question, not a long list of libraries. Follow the route from Python foundations to a checked summary, a clear chart and a finding you can explain.

Python for data analysis means using code to read, inspect, prepare, summarise and visualise data. It is useful when you need a process you can review and repeat. The code handles the operations; you still decide which records belong in the calculation and what the result means.

Imagine opening a spreadsheet with hundreds of rows and several blank cells. Removing every incomplete row might seem sensible. But a blank in an unrelated column could make you discard a measurement you actually need.

That is the kind of decision this guide will help you make. You will work through a real dataset and produce a checked summary, a labelled chart and a finding you can explain.

What can you do with Python for data analysis?

Python helps turn a question about records into a sequence of explicit steps. You can inspect a CSV export, identify missing information, select relevant observations, compare groups and export the result.

For example, you might investigate how order values differ between categories or how recorded service requests vary by month. Before calculating, you need to understand what each row represents, which period it covers and what the fields mean.

Analysis step

Useful output

Inspect the data.

A record of columns, types and missing values.

Prepare the relevant records.

A defined analysis table with documented exclusions.

Compare groups.

Counts, totals or other appropriate summaries.

Visualise the result

A chart with clear labels and units.

Explain the finding.

A short answer stating its scope and limitations.

Analysis answers a question. Automation repeats defined steps. They can work together, but repeating a calculation does not establish that it is right.

You also do not need machine learning to complete a useful analysis. This guide uses descriptive analysis: explaining what is present in the observed data, without building a predictive model.

Should you use Python, Excel or both?

Choose according to the task and the people who will use the result.

Your situation

A useful starting point

You need a quick calculation or an editable workbook.

Excel may be convenient.

You want processing rules recorded as reusable code.

Consider Python.

You prepare data in code but colleagues need a spreadsheet.

Use Python and Excel together.

Excel also supports repeatable data preparation, including Power Query. Python is not automatically faster or more appropriate simply because a file is large. The operations, available memory and collaboration needs matter too.

For the detailed comparison, use Python vs Excel for Data Analysis: Which Should You Learn?

Here, the aim is to understand a coded analysis from input to conclusion—not to replace every spreadsheet task.

How much Python do you need before starting?

For the practical section, you should recognise variables, strings and numbers, lists and dictionaries, simple conditions and function calls. You should also know how to run code.

You do not need advanced software engineering or a complete understanding of every Python library. The example introduces the table operations it uses.

Three conventions will help:

  • import pandas as pd loads pandas and gives it the conventional short name pd.

  • penguins = ... assigns a result to a variable named penguins.

  • penguins.head() calls an operation on that table; the parentheses indicate a function or method call.

If those ideas are new, read the orientation sections first, practise the foundations and return to the example. Copying code can help you begin, but aim to explain what each block receives and produces.

As your work grows, loops and functions help organise repeated steps. You can develop those skills alongside increasingly demanding analyses rather than attempting every topic at once.

Understand the tools before installing them

The names often appear together, but they do different jobs.

Tool

Its role

Python

The language used to express operations and rules.

Jupyter Notebook

A document containing executable code cells, notes and outputs.

pandas

Tools for labelled tables, selection and grouped calculations.

NumPy

Numerical arrays and operations used across the scientific Python ecosystem.

Matplotlib

Tools for building and labelling charts.

A pandas DataFrame is a table with labelled columns and an index identifying its rows. A series is a one-dimensional labelled structure, such as a selected column.

You will mainly use pandas and matplotlib here. NumPy appears in the environment check, but this first example does not require a separate NumPy tutorial.

Jupyter is a working environment, not another analysis language. Code runs through a kernel, the process executing the notebook’s instructions. A notebook opened in a browser can still be running locally on your computer.

“Roles of Python, Jupyter Notebook, pandas, NumPy and Matplotlib in data analysis.”

The pandas introductory tutorials, NumPy beginner documentation and Matplotlib quick-start guide explain these tools in more depth.

Set up your first analysis workspace

[Download placement: notebook, source CSV, data dictionary and reference outputs]

Extract the supplied learning package into a project folder. Keep python_data_analysis.ipynb beside penguins.csv. The package also contains reference outputs and source notes.

Install Python 3 first if it is not already available. Open a terminal in the project folder. A virtual environment gives this project its own package environment rather than mixing its dependencies with other work.

Windows: run these in the terminal, one command at a time.

python -m venv. venv

venv\Scripts\python.exe -m pip install notebook pandas numpy matplotlib

.\.venv\Scripts\python.exe -m notebook

macOS or Linux: run these in the terminal.

python3 -m venv .venv

venv/bin/python -m pip install notebook pandas numpy matplotlib

.venv/bin/python -m notebook

On Windows, use py -m venv .venv instead if py is your Python launcher. These commands use the environment’s interpreter directly; activation is not required.

Open the supplied notebook. Code cells run instructions; text cells explain the work. Execute code cells from top to bottom with Shift+Enter. If a package is missing, check that the notebook kernel belongs to the environment where you installed it.

Run this notebook cell to import the tools and display their versions. The first line makes charts display inside the notebook.

%matplotlib inlinefrom pathlib import import sys import pandas as pd import numpy as np npimport matplotlibimport matplotlib.pyplot as plt print("Python:", sys.version.split()[0]) print("pandas:", pd.__version__) print("NumPy:", np.__version__) print("Matplotlib:", matplotlib.__version__)

The calculations below were checked with Python 3.12.14, pandas 2.2.3, NumPy 2.3.5 and Matplotlib 3.10. 8. These are not promises about every environment.

See the official Jupyter installation instructions and Python virtual environment guidance for setup details.

Follow a question-to-conclusion workflow

A useful analysis has a sequence you can explain:

Define the question → understand the source → inspect → prepare → summarise → visualise → explain and share.

These are connected decisions. Discovering missing measurements may change which comparison is possible. A chart may show that a single summary hides useful variation. You may need to return to an earlier step.

For the first exercise, keep the scope small. Answer one descriptive question, keep track of excluded records and produce one main chart.

Python analysis workflow from defining a question to inspecting data, choosing relevant records and explaining the result.

Practical example: compare penguin body mass

Define the question and understand the records

Our question is:

How does median body mass compare across the three penguin species in this observed sample, and how many usable measurements support each figure?

The Palmer Penguins data describe sampled adult penguins around Palmer Station, Antarctica, during 2007–2009. The simplified CSV contains 344 records and eight columns.

The data were collected by Kristen Gorman and the Palmer Station Long Term Ecological Research programme. The curated package is credited to Allison Horst, Alison Hill and Kristen Gorman. The project states that the data are available under CC0. 

 Sources: dataset introduction and provenance and field definitions.

This is a real ecological dataset used for learning, not a fictional business case. You can apply the same question-and-check approach to workplace tables.

Load the CSV into a DataFrame

Run the following cell:

data_path = Path("penguins.csv")if not data_path.is_file():    raise FileNotFoundError("Keep penguins.csv in the notebook working folder.")penguins = pd.read_csv(data_path)required = {"species", "body_mass_g"}if not required.issubset(penguins.columns):    raise ValueError("The CSV needs species and body_mass_g columns.")penguins.head()

pd.read_csv() reads the file into a DataFrame. head() displays its first five rows so you can inspect the structure.

Two fields are central to our question: species identifies the group, and body_mass_g gives body mass in grams. The other columns include island, measurements, sex and study year.

If the file is not found, check the notebook’s working folder rather than changing unrelated code. Keep the supplied source unchanged so your results remain comparable with the reference outputs.

Inspect the data before changing it

print("Rows and columns:", penguins.shape)print("\nData types:\n", penguins.dtypes)print("\nMissing values:\n", penguins.isna(). sum())print("\nExact repeated rows: ", penguins.duplicated(). sum())print("\nSource records by species:\n", penguins.groupby("species"). size())

The supplied file has this missing-value pattern:

Column

Missing values

species

0

island

0

bill_length_mm

2

bill_depth_mm

2

flipper_length_mm

2

body_mass_g

2

sex

11

year

0

There are no exact repeated rows across the eight fields in this source copy. We therefore have no reason to remove exact duplicates in this example.

Missing values do require a decision. Our question compares body mass by species. It does not compare male and female penguins, so an unknown sex value does not automatically prevent a record from contributing.

Checkpoint: Confirm (344, 8) and the missing-value counts before continuing. Different results may mean you are using a changed file or table.

Choose a cleaning rule that fits the question

Keep the original penguins table. Create a separate table using the fields needed for this calculation, and retain the excluded records:

missing_required = penguins[["species", "body_mass_g"]].isna(). any(axis=1)excluded = penguins.loc[missing_required].copy()excluded. insert(0, "source_row", excluded.index + 2)analysis = penguins.loc[~missing_required, ["species", "body_mass_g"]].copy()print("Source records:", len(penguins))print("Included records:", len(analysis))print("Excluded records:", len(excluded))print("Records after dropping every incomplete row: ", len(penguins. dropna()))

Expected counts:

Result

Records

Source

344

Included in this comparison

342

Excluded because required information is missing

2

Retained after removing every incomplete row

333

The blanket approach would exclude nine additional records with usable body-mass measurements. That is unnecessary for this question.

This does not establish that missing information is harmless or that filtering never affects results. We have chosen a stated rule and have not estimated the missing masses.

copy() creates a separate analysis table. source_row records the original CSV row for the excluded entries, including the header row in the numbering.

The pandas missing-data guide explains the available operations. For deeper practice with selection and cleaning, use  Pandas for Data Analysis: A Practical Beginner’s Guide.

Summarise body mass and report usable counts

The median is the middle value after sorting the measurements. With an even number of measurements, it is the average of the two middle values. It is one way to describe a group’s centre, not a complete description of its distribution.

summary = (    analysis.groupby("species", as_index=False)    .agg(        measurements=("body_mass_g", "count"),        median_body_mass_g=("body_mass_g", "median"),    )    .sort_values("species")    .reset_index(drop=True))if len(penguins) != len(analysis) + len(excluded):    raise ValueError("Included and excluded counts do not reconcile.")if int(summary["measurements"].sum()) != len(analysis):    raise ValueError("Summary counts do not match the analysis table.")summary

The result should be:

Species

Usable body-mass measurements

Median body mass

Adelie

151

3,700 g

Chinstrap

68

3,700 g

Gentoo

123

5,000 g

groupby() gathers records by species. agg() calculates the named summaries. The checks confirm that the included and excluded counts reconcile and that summary counts match the analysis table.

The usable counts total 342. A column count excludes missing entries; a group row count answers a different question. Here, the body-mass fields in the analysis table are complete.

Do not add the medians or average them to produce an overall median. That requires calculating from the relevant underlying measurements.

Create a chart with clear labels and units

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained") bars = axe.bar (    summary["species"],    summary["median_body_mass_g"],    color=["#426A8C", "#527F98", "#247F86"],    width=0.6,)ax.set_title(    "Median body mass in the Palmer Penguins sample",    loc="left",    pad=18,)ax.set_xlabel("Species and usable body-mass measurements"), measurements")ax.set_ylabel("Median body mass (g)")ax.set_ylim(0, 5700)ax.set_xticks(range(len(summary)))ax.set_xticklabels([f"{row.species}\nn = {row.measurements}"    for row in summary. itertuples(index=False))ax.bar_label(bars,    labels=[f"{value:,.0f} g" for value in summary["median_body_mass_g"]],    padding=5)ax.spines[["top", "right"]].set_visible(False)ax.yaxis. grid(True, color="#E5EAEE", linewidth=0.7)ax.set_axisbelow(True)plt.show()

The chart displays the group medians, starts its value axis at zero and labels both grams and usable sample sizes. The bars do not show the full distributions.

Median body mass in the analysed Palmer Penguins sample: Adelie 3,700 g, Chinstrap 3,700 g and Gentoo 5,000 g, with usable sample counts.

A box plot could extend this exercise by showing more of each distribution. First make sure you can explain what this simpler chart represents and what it leaves out.

Explain the finding without overstating it

A suitable finding is:

In the analysed sample, Gentoo penguins had a higher median body mass: 5,000 g across 123 usable measurements. Adelie and Chinstrap each had a median of 3,700 g, supported by 151 and 68 measurements, respectively. Two records with missing body mass were excluded.

Then state the limits. These are sampled adults from a particular study context, not every penguin population. Equal medians do not mean identical distributions. We have not established why the groups differ or assessed the effects of the missing measurements.

Species and islands are also not fully crossed in this file: Chinstrap records occur on Dream, and Gentoo records on Biscoe. This simple comparison cannot isolate an island effect.

You have answered a descriptive question. You have not demonstrated causation or built a prediction model.

Export the result and check a fresh run

output_dir = Path("outputs")output_dir.mkdir(exist_ok=True)summary.to_csv (output_dir / "body_mass_summary.csv", index=False)excluded.to_csv (output_dir / "excluded_measurements.csv", index=False)fig.savefig(output_dir / "median_body_mass.png", dpi=180)print("Saved summary, excluded-record list and chart in outputs.")

The summary CSV records the calculated figures. The excluded-record file preserves the two observations left out of this comparison. The PNG is the chart for sharing.

Rerunning this cell replaces those three named outputs; it does not write to penguins.csv.

Before treating your notebook as finished, restart its kernel and run all cells in order. Compare the counts, table and chart with the reference outputs. This helps reveal a dependency on an earlier experiment or a cell run in the wrong order.

Avoid mistakes that change the meaning of your results

Mistake

Why it matters

Better check

Removing every row containing a blank

Useful records may disappear because unrelated fields are missing.

Name the fields required by the question.

Converting every number-like field to a number

Identifiers such as 00125 can lose their representation.

Read the field definition first.

Deleting matching rows automatically

Repeated observations are not necessarily duplicate errors.

Establish what identifies a record.

Reporting a summary without usable counts

Readers cannot assess how many measurements support it.

Put counts beside the result.

Treating a chart as an explanation of cause

A visual difference does not establish why it exists.

Separate description from explanation.

Running notebook cells in an arbitrary order

Old variables can hide missing steps.

Restart and execute from the beginning.

The same habits matter when importing Excel workbooks or other CSVs. Check types, units and data meaning rather than assuming the file extension guarantees a clean table.

“Six checks covering the analysis question, data, cleaning decisions, summary calculations, chart and conclusion.”

Choose your next project or automation

Choose the next guide according to what you want to do, rather than treating every topic as a prerequisite.

Your next goal

Relevant guide

Practise a new analytical question.

Python Data Analysis Projects to Build Practical Skills

Repeat a stable spreadsheet-reporting process.

How to Automate Excel with Python: A Practical Guide

Identify other routine tasks worth scripting.

10 Python Automation Tasks That Can Save Hours

For a small extension here, compare the same sample using a different summary or investigate the distribution with an explained chart. State the new question first. Do not add complexity simply to make the notebook longer.

A useful next step is one you can define, complete and check independently. If you understand the example but struggle to adapt a condition or file path, practise that specific gap before moving to a larger project.

Build the foundations you still need

For a broader context on the tools used in analytical work, read SQL, Python, Power BI: Skills Germany Wants.

If you need structured foundations, the Python Programming Bootcamp (Data Analysis & Automation) covers programming logic, structured data and files, pandas analysis, visualisation and automation.

Use the syllabus to assess your learning gap. This particular penguin project and every named tool are not confirmed course assignments or syllabus items.

 View the course syllabus and prerequisites.

Frequently Asked Questions

01 Is Python suitable for a complete beginner in data analysis? +

Yes, but begin with the language and execution basics before adapting analysis code. You can read this guide for orientation, then practise the prerequisites needed for its worked example. A single tutorial does not replace sustained practice.

02 How much Python should I know before using pandas? +

Know variables, basic data types, lists, dictionaries, conditions and function calls, and be able to run code. Extend loops and reusable functions as your tasks grow. You do not need advanced programming before starting simple table work.

03 Do I need to learn NumPy before pandas? +

You do not need a separate NumPy course to begin the table operations here. Understanding arrays and numerical operations becomes useful as your work develops. Start with the tools needed to answer your first question.

04 Is Jupyter Notebook required for Python data analysis? +

No. You can use scripts or other suitable environments. Notebook is useful for learning because it keeps code, results and explanations together. Its convenience does not remove the need to check execution order and dependencies.

05 Can Python analyse CSV and Excel files? +

Yes. Libraries such as pandas support both, with appropriate dependencies and options. Check delimiters, sheets, headers, data types and units. Reading a workbook into a table does not preserve every workbook feature when you export it again.

06 Should I fill or remove missing values? +

Choose according to the question and data meaning. Report which fields are missing, justify the treatment and show its effect on included records. Filling values introduces assumptions; removing records can also change the analysis.

07 Do I need machine learning to analyse data with Python? +

No. Inspection, grouped summaries and charts can answer useful descriptive questions. Predictive modelling introduces additional requirements and evaluation. Complete a clear, checked analysis before deciding whether a model is needed for a different question.

08 What should my first completed analysis contain? +

A clear question, documented source, readable code, explained preparation decisions, checked results, an appropriate visual and a short finding with limitations. Include the run instructions and environment information so another reader can review your work.

Here your growth begins.

Unleash your potential. Learn anytime, anywhere.