DEV Community

Python for Data Analytics: A Hands-On Field Guide

So you've decided to learn Python for data analytics. Good call. It's the language most teams actually use day-to-day for cleaning data, exploring it, and turning messy CSVs into decisions. This tutorial is written the way I wish someone had taught me — by doing, not just reading.

We'll cover the real workflow: getting your environment set up, loading data, cleaning it, exploring it, and answering actual questions with it. Every section has code you can run, an exercise, and the mistakes I've made so you don't have to.

Let's get to it.

What You'll Build
By the end of this tutorial you'll have analyzed a real sales dataset and produced a small report that answers questions like:

Which product category drives the most revenue?

How do sales trend across the year?

Which regions are underperforming?

No toy examples. Real code, real workflow.

  1. Setting Up Your Environment First, you need Python. I recommend Python 3.10+. If you're on Windows, install it from python.org and check "Add Python to PATH" during setup. On macOS, Homebrew works well: brew install python.

Next, create an isolated environment so your projects don't fight each other over package versions.

bash

Create and activate a virtual environment

python -m venv .venv

Windows

.venv\Scripts\activate

macOS/Linux

source .venv/bin/activate
Now install the core data stack:

bash
pip install pandas numpy matplotlib seaborn jupyter
That's your toolkit for this tutorial:

pandas — tabular data, the workhorse

numpy — fast numerical operations underneath pandas

matplotlib / seaborn — plotting

jupyter — an interactive notebook for exploring

Common error #1: pip says "command not found." Fix: use python -m pip install ... instead, or make sure Python is on your PATH.

  1. Your First Dataset We'll use a small, realistic sales dataset. You can find a version of this in my GitHub repo:

GitHub example: github.com/yourname/python-data-analytics-tutorial — clone it and grab sales_data.csv.

The file looks like this:

text
order_id,date,region,category,units,unit_price
1001,2024-01-05,North,Electronics,3,299.99
1002,2024-01-12,South,Clothing,5,49.99
...
Load it with pandas:

python
import pandas as pd

df = pd.read_csv("sales_data.csv")
print(df.head())
df.head() shows the first five rows. This is your first look at the data — always do this before anything else.

  1. Know Your Data Before You Trust It Before analyzing, get a feel for what you're working with.

python

Shape: how many rows and columns

print(df.shape)

Column names and data types

print(df.info())

Quick statistical summary of numeric columns

print(df.describe())
df.info() tells you if a column is stored as a number, text, or date. This matters more than you'd think — a column that looks like numbers but is stored as text will silently break your math.

Common error #2: Your date column shows as object instead of a date. Fix it:

python
df["date"] = pd.to_datetime(df["date"])

  1. Cleaning the Data (The Part Nobody Glamorizes) Real data is messy. Here's the honest truth: 60–80% of analytics work is cleaning. Let's deal with the usual suspects.

Missing values
python

How many missing values per column?

print(df.isnull().sum())
Then decide what to do. Options:

python

Drop rows with missing values in a critical column

df = df.dropna(subset=["region"])

Fill missing numeric values with the median (robust to outliers)

df["unit_price"] = df["unit_price"].fillna(df["unit_price"].median())
Best practice: Never blindly drop rows. Understand why data is missing first. If a whole region is missing, that's a data collection problem, not a "drop it" problem.

Duplicates
python

Check for duplicate rows

print(df.duplicated().sum())

Remove them

df = df.drop_duplicates()
Data types
python

Force the right types

df["units"] = df["units"].astype(int)
df["unit_price"] = df["unit_price"].astype(float)
Creating a derived column
python

Revenue per order

df["revenue"] = df["units"] * df["unit_price"]
Now you have a clean, usable dataset. This is the foundation everything else builds on.

  1. Exploring and Answering Questions This is where it gets fun. Let's answer the questions from the start.

Revenue by category
python
category_revenue = df.groupby("category")["revenue"].sum().sort_values(ascending=False)
print(category_revenue)
Sales trend over time
python

Resample by month and sum revenue

monthly = df.set_index("date")["revenue"].resample("M").sum()
print(monthly)
Region performance
python
region_stats = df.groupby("region").agg(
total_revenue=("revenue", "sum"),
avg_order=("revenue", "mean"),
orders=("order_id", "count")
).sort_values("total_revenue", ascending=False)

print(region_stats)
groupby + agg is the single most useful pandas pattern you'll learn. Master it.

Performance tip: When working with large data, filter early. df[df["region"] == "North"] before grouping is much faster than grouping everything and filtering after.

  1. Visualizing the Results Numbers are good; pictures are better when presenting to stakeholders.

python
import matplotlib.pyplot as plt
import seaborn as sns

Revenue by category

category_revenue.plot(kind="bar", title="Revenue by Category")
plt.ylabel("Revenue")
plt.tight_layout()
plt.show()

Monthly trend

monthly.plot(kind="line", marker="o", title="Monthly Revenue Trend")
plt.ylabel("Revenue")
plt.tight_layout()
plt.show()
Seaborn makes nicer-looking charts with less effort:

python
sns.barplot(data=df, x="category", y="revenue", estimator=sum)
plt.title("Revenue by Category")
plt.show()
Best practice: Label your axes. A chart without axis labels is a mystery, not an insight.

  1. Practical Exercise Here's your chance to practice. Spend 20 minutes on this before reading the solution.

Task: Using the same dataset, find:

The top 5 orders by revenue.

Which region has the highest average order value.

Whether revenue grew or shrank between the first and last six months of the year.

Starter hints:

python

Top 5 orders

top_orders = df.nlargest(5, "revenue")

Average order value by region

aov = df.groupby("region")["revenue"].mean().sort_values(ascending=False)
Solution (check after attempting):

python

1. Top 5 orders

print(df.nlargest(5, "revenue"))

2. Highest average order value

print(df.groupby("region")["revenue"].mean().idxmax())

3. First vs second half of year

df["half"] = df["date"].dt.month.apply(lambda m: "H1" if m <= 6 else "H2")
print(df.groupby("half")["revenue"].sum())
Did your answers match your intuition? If not, dig into why — that's where real learning happens.

  1. Troubleshooting Common Errors Here's a cheat sheet for the errors you'll actually hit:

Error What it means Fix
KeyError: 'column' Column name doesn't exist Check spelling and df.columns
ValueError: cannot convert Wrong data type in a column Inspect values with df["col"].unique()
SettingWithCopyWarning You're modifying a slice of a DataFrame Use .copy() or operate on the original
MemoryError Dataset too big for RAM Read in chunks or use dtype to save memory
ImportError Package not installed pip install
The SettingWithCopyWarning one deserves attention. It's a warning, not an error, but it hides real bugs:

python

This can silently fail to modify the original df

subset = df[df["region"] == "North"]
subset["flag"] = 1 # warning!

Safer:

subset = df[df["region"] == "North"].copy()
subset["flag"] = 1 # no warning
Best practice: Use .copy() whenever you're creating a filtered subset you intend to modify.

  1. Performance Tips for Larger Data When your data outgrows a few hundred thousand rows, these matter:

Use dtype to save memory. Downcast numeric columns:

python
df["units"] = pd.to_numeric(df["units"], downcast="integer")
Filter before you transform. Do heavy work on a subset.

Vectorize, don't loop. Avoid for loops over rows; use pandas operations instead.

Use inplace=False (the default). Chaining operations like df.dropna().groupby(...) is often faster than repeated in-place steps.

For truly huge data, consider chunked reading or a tool like Polars or DuckDB.

python

Reading a huge file in chunks

chunks = pd.read_csv("big_file.csv", chunksize=100_000)
for chunk in chunks:
# process each chunk
pass

  1. Best Practices Checklist Always df.head() and df.info() first. Never analyze blind.

Document your cleaning steps. Comment why you dropped or filled data.

Use consistent naming. df, clean_df, monthly — be predictable.

Save your cleaned data. clean_df.to_csv("sales_clean.csv", index=False) so you don't re-clean.

Write small functions for repeated logic instead of copy-pasting.

Version your code with Git. Even solo projects benefit.

  1. Where to Go Next You've covered the core loop: load → clean → explore → visualize → communicate. Here's how to level up:

Pandas documentation — the official docs are genuinely excellent.

Kaggle — free datasets and notebooks to practice on real problems.

"Python for Data Analysis" by Wes McKinney (pandas' creator) — the definitive book.

GitHub — read other people's notebooks. You'll learn patterns you'd never invent yourself.

A note on structured learning
If you're in Bangalore and want a guided path rather than self-teaching, there are many data analytics training and placement programs in Bangalore that combine structured coursework with placement support. A good one will teach you exactly this workflow — pandas, SQL, visualization, and real portfolio projects — and then help you get interviews. Just vet any program carefully: check reviews, ask about placement rates (not just promises), and confirm they teach current tools rather than outdated curricula. Structured training works well if you're the kind of learner who needs deadlines and accountability; self-study works if you're disciplined. Both are valid — pick what fits how you learn.

Wrap-Up
You now have a complete, repeatable workflow for analyzing data with Python. The tools are simple, but the habit of checking your data, cleaning it deliberately, and asking clear questions is what separates useful analysis from noise.

Here's your homework: take any dataset you care about — your spending, your fitness tracker, a public dataset — and run it through this exact pipeline. Then share what you found. That's the best way to make it stick.

Happy analyzing. 🐍

Want to see the full working code? Check out the companion repo linked in Section 2. If you found this useful, follow along for more hands-on data tutorials.

Top comments (0)