Thuta Learning
Python
IntermediateProgrammingBeginner

Pandas Tutorial (Enhanced)

PythonLesson 3535 min

What you'll walk away with

  • Build a DataFrame from a dictionary and inspect it with shape, dtypes and head()
  • Explain the difference between selecting one column (a Series) and a list of columns (a DataFrame)
  • Filter rows with boolean conditions combined using & and |
  • Produce per-group summaries such as count and sum with groupby and agg
  • Update values in one step with loc instead of chained assignment

Explain it simply

pandas in plain language

pandas is like a spreadsheet inside Python. A DataFrame is a table with named columns and labelled rows, and a Series is a single column from that table. Each column is backed by an array, much like NumPy, so you can compute on a whole column at once.

Its everyday job is reading data from CSV, Excel, JSON or a SQL database, then cleaning, filtering, grouping and summarising it. A question like 'how much did each city sell?' becomes one or two lines instead of a loop.

Problem → Why → Solution

The problem: reporting from a list of dictionaries

You receive orders as a list of dictionaries and need total revenue per city. One loop computes revenue, a dictionary accumulates totals per city, and sorted() orders the result, so the code keeps growing. When a manager adds 'only orders with quantity above 2', you rewrite the loops again.

report_by_hand.py
orders = [
    {"city": "Yangon", "qty": 3, "price": 2.5},
    {"city": "Mandalay", "qty": 1, "price": 4.0},
    {"city": "Yangon", "qty": 2, "price": 4.0},
]

totals = {}
for o in orders:
    revenue = o["qty"] * o["price"]
    totals[o["city"]] = totals.get(o["city"], 0) + revenue

report = sorted(totals.items(), key=lambda kv: kv[1], reverse=True)
print(report)

What pandas changes

In pandas, revenue is one expression multiplying two columns, a filter is one condition, and the report is a single groupby. The logic reads like a description of the data, so adding a new condition is easy, and pandas handles missing values, data types and sorting consistently.

Core concept: index, columns, filters and groupby

A DataFrame has three parts: column names, an index of row labels, and one array of values per column. If you do not supply an index, pandas uses a RangeIndex of 0, 1, 2 and so on. Each column has its own dtype, which df.dtypes reports; in pandas 3 text columns use the str dtype by default, while older versions showed them as object.

Selecting with one string, df["qty"], gives a Series; selecting with a list, df[["qty", "price"]], gives a new DataFrame. To choose rows and columns together, use loc for labels and iloc for integer positions. df.loc[row_condition, "qty"] reads as 'the qty column of the rows where the condition holds'. Note that a loc label slice includes its end point, while iloc follows Python's exclusive slicing.

SyntaxWhat it selects
df["qty"]one column, as a Series
df[mask]the rows where mask is True
df.loc[2, "qty"]the qty value of index label 2
df.iloc[0:2, 1]first two rows, second column

When you add or multiply two Series, pandas pairs values by index label, not by position. Adding two Series with different indexes produces NaN wherever a label has no partner, a behaviour called alignment.

Filtering works like a NumPy mask: df["qty"] > 2 returns a Series of True and False, one per row, and df[mask] keeps the True rows. To combine conditions, use & and | instead of and/or, and wrap each condition in parentheses because of operator precedence.

groupby follows a split-apply-combine pattern: split the rows by the values of a key column, apply a function such as sum, mean or count to each group, then combine the results into a new table indexed by the group key. agg(["count", "sum"]) or named aggregation such as agg(total=("revenue", "sum")) produces several summaries at once.

A DataFrame is a set of labelled columns
  1. Look with dtypes and head()
  2. Derive columns with expressions
  3. Pick rows with a boolean mask
  4. groupby: split, apply, combine

Whenever you feel like looping over rows, first look for a way to express the step on whole columns.

General pattern

python
import pandas as pd

df = pd.DataFrame({"col_a": [...], "col_b": [...]})   # or pd.read_csv(path)
df.shape, df.dtypes, df.head()

df["new_col"] = df["col_a"] * df["col_b"]
subset = df[(df["col_a"] > x) & (df["col_b"] == y)]
df.loc[row_mask, "col_b"] = new_value
summary = df.groupby("key")["value"].agg(["count", "sum"])
summary.sort_values("sum", ascending=False)

Load and inspect the data, derive columns with expressions, filter with masks, use loc to update, and finish with a groupby summary.

Worked example: a café order report

The program below builds a DataFrame of six café orders from three cities. It replaces the loops from the problem section with a revenue column, a boolean filter, a loc lookup and a groupby report, and the dtypes in the output show pandas 3's str dtype for text.

cafe_orders.py
import pandas as pd

orders = pd.DataFrame({
    "order_id": [101, 102, 103, 104, 105, 106],
    "city": ["Yangon", "Mandalay", "Yangon", "Bago", "Mandalay", "Yangon"],
    "product": ["tea", "coffee", "coffee", "tea", "tea", "cake"],
    "qty": [3, 1, 2, 5, 2, 4],
    "price": [2.5, 4.0, 4.0, 2.5, 2.5, 3.0],
})
print(orders.shape)
print(orders.dtypes)

orders["revenue"] = orders["qty"] * orders["price"]   # whole column at once
print(orders.head(3))

big = orders[orders["revenue"] >= 10]                  # boolean filter
print(big[["order_id", "city", "revenue"]])

print(orders.loc[orders["city"] == "Yangon", "qty"].sum())

by_city = (
    orders.groupby("city")["revenue"]
    .agg(["count", "sum"])
    .sort_values("sum", ascending=False)
)
print(by_city)

Code breakdown

  1. Inspect the tableprint(orders.dtypes)

    Shows each column's dtype: order_id and qty are int64, price is float64, city and product are str. A numeric column showing up as str must be fixed before any maths.

  2. Derive a columnorders["revenue"] = orders["qty"] * orders["price"] # whole column at once

    Multiplies two Series aligned by index and stores the result as a new column. All six rows are computed together, with no loop.

  3. Filter rowsbig = orders[orders["revenue"] >= 10] # boolean filter

    The mask has six True/False values and only orders 104 and 106 survive. Notice in the output that they keep their original index labels, 3 and 5.

  4. loc with a conditionprint(orders.loc[orders["city"] == "Yangon", "qty"].sum())

    loc[row condition, column] picks the qty of the Yangon rows only, and summing gives 3 + 2 + 4 = 9.

  5. Group and sort.agg(["count", "sum"])

    groupby("city") splits rows by city and agg computes count and sum of revenue for each group. The result is indexed by city, and sort_values orders it from the largest total.

You should see
(6, 5)
order_id      int64
city            str
product         str
qty           int64
price       float64
dtype: object
   order_id      city product  qty  price  revenue
0       101    Yangon     tea    3    2.5      7.5
1       102  Mandalay  coffee    1    4.0      4.0
2       103    Yangon  coffee    2    4.0      8.0
   order_id    city  revenue
3       104    Bago     12.5
5       106  Yangon     12.0
9
          count   sum
city
Yangon        3  27.5
Bago          1  12.5
Mandalay      2   9.0

Reading files, writing files and inspecting data

In practice you load a DataFrame from a file more often than from a dictionary. pd.read_csv, pd.read_json, pd.read_sql and pd.read_excel (which needs an engine such as openpyxl installed) all return a DataFrame, and to_csv(path, index=False) writes it back without an extra index column.

inspect.py
import io

import pandas as pd

csv_text = "city,qty\nYangon,3\nBago,\nMandalay,2\n"
df = pd.read_csv(io.StringIO(csv_text))    # same call works with a file path

df.info()                       # prints a summary itself and returns None
print(df.isna().sum())          # missing values per column
print(df.describe())            # count, mean, std, min, quartiles, max

Do not wrap info() in print()

df.info() prints its summary directly and returns None, so print(df.info()) adds a stray None after the summary. In the output you will also notice that qty became float64, because a missing value forces an integer column to float.

In real projects

pandas in real projects

Data analysts, backend developers and ML engineers all reach for pandas daily. The shape of the work is usually the same: read from a source, fix dtypes and missing values, derive columns, filter and group, then export a report or a model input. For files larger than memory, teams switch to chunked reading or a database rather than one giant DataFrame.

  • Business reporting: pull sales with read_sql, summarise by month with groupby(["region", "month"]), and send a weekly Excel or CSV export.
  • Data-cleaning pipelines: keep drop_duplicates, fillna, astype and str.strip in one function and rerun the same steps whenever a new raw file arrives.
  • Machine learning: select feature columns from a CSV, encode categories with pd.get_dummies, and hand df.to_numpy() to a model.

Common mistakes

Common pandas mistakes

Updating values with chained assignment

df[df["qty"] > 2]["price"] = 0 indexes twice, and the first step returns a temporary object. Under pandas 3's Copy-on-Write this assignment never changes the original df; you only get a ChainedAssignmentError warning. Write it in one step: df.loc[df["qty"] > 2, "price"] = 0.

Combining conditions with and/or

df[df.qty > 1 and df.price < 3] raises 'The truth value of a Series is ambiguous', because Python's and tries to turn a whole Series into one True or False. Write (df.qty > 1) & (df.price < 3) with parentheses; without them & binds tighter than the comparisons.

Forgetting the index after filtering

A filtered frame keeps its original labels, so big.loc[0] can raise KeyError. Use iloc[0] when you mean the first position, or call reset_index(drop=True) to renumber from 0.

Best practices

Best practices

  • Check shape, dtypes and isna().sum() right after loading a file.
  • Avoid looping with iterrows(); use column expressions or groupby instead.
  • Update values with a single loc[row, column] step.
  • Write cleaning steps as functions that return a new DataFrame instead of mutating their input.

Mini challenge

Mini challenge: a team timesheet report

You get a timesheet for three teams as a DataFrame, and one person's hours are missing. Write clean, which fills missing hours with 0 and adds a pay column, and team_report, which gives head count, total hours and total pay per team. Then show who worked overtime and the top earner in each team.

  • clean returns a new DataFrame without mutating its input
  • team_report uses named aggregation for people, hours and pay, sorted by pay
  • Select people with more than 38 hours using loc
  • Find each team's highest-paid row with groupby plus idxmax
timesheet.py
import pandas as pd

timesheet = pd.DataFrame({
    "name": ["Aye", "Ko Ko", "Mya", "Zaw", "Hla", "Nandar"],
    "team": ["web", "web", "data", "data", "data", "ops"],
    "hours": [38, None, 42, 35, 40, 30],
    "rate": [12.0, 11.5, 15.0, 14.0, 15.0, 10.0],
})


def clean(df: pd.DataFrame) -> pd.DataFrame:
    # TODO: copy-safe fill of missing hours with 0, then add pay = hours * rate
    ...


def team_report(df: pd.DataFrame) -> pd.DataFrame:
    # TODO: groupby team -> people (count), hours (sum), pay (sum), sorted by pay
    ...


# TODO: print missing counts before/after, the report,
#       the overtime rows (hours > 38) and the top earner per team

Expected: Missing hours go from 1 to 0; the report lists data first with pay 1720.0, then web 456.0 and ops 300.0. Overtime shows Mya (42.0) and Hla (40.0), and the top earners per team are Mya, Nandar and Aye.

Show hint

df.assign(hours=df["hours"].fillna(0)) returns a new frame. Named aggregation looks like agg(people=("name", "count")). groupby("team")["pay"].idxmax() returns index labels you can pass straight to loc.

Show solution
timesheet.py
import pandas as pd

timesheet = pd.DataFrame({
    "name": ["Aye", "Ko Ko", "Mya", "Zaw", "Hla", "Nandar"],
    "team": ["web", "web", "data", "data", "data", "ops"],
    "hours": [38, None, 42, 35, 40, 30],
    "rate": [12.0, 11.5, 15.0, 14.0, 15.0, 10.0],
})


def clean(df: pd.DataFrame) -> pd.DataFrame:
    """Return a new frame: missing hours become 0, plus a pay column."""
    out = df.assign(hours=df["hours"].fillna(0))
    out["pay"] = out["hours"] * out["rate"]
    return out


def team_report(df: pd.DataFrame) -> pd.DataFrame:
    return (
        df.groupby("team")
        .agg(people=("name", "count"), hours=("hours", "sum"), pay=("pay", "sum"))
        .sort_values("pay", ascending=False)
    )


sheet = clean(timesheet)
print("missing before:", int(timesheet["hours"].isna().sum()),
      "after:", int(sheet["hours"].isna().sum()))
print(team_report(sheet))

overtime = sheet.loc[sheet["hours"] > 38, ["name", "hours"]]
print(overtime.to_string(index=False))

top = sheet.loc[sheet.groupby("team")["pay"].idxmax(), ["team", "name", "pay"]]
print(top.to_string(index=False))

Quick quiz 1 / 3

If df is a DataFrame, what is type(df[["qty"]])?

Quick quiz 2 / 3

In pandas 3, what happens when you run df[df["qty"] > 2]["price"] = 0?

Quick quiz 3 / 3

Which expression gives total revenue per city?

What to remember

  • A DataFrame is an index, column names and one typed array per column.
  • A string selects a Series, a list selects a DataFrame, and loc/iloc select rows and columns together.
  • Combine filter conditions with & and |, each wrapped in parentheses.
  • groupby is split-apply-combine; update values with loc rather than chained assignment.

pandas — Getting Started — pandas

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Pandas Tutorial (Enhanced) | Thuta Learning