Skip to content

Module 16 · External Libraries and APIs — topic 6 of 12

Pandas introduction

Tabular data with pandas: Series and DataFrames, creating and reading data, selecting columns and filtering rows, sorting, grouping and aggregating, pivot tables, and summary statistics.

Beginner 12 min read·Lesson 240 of 306 in Python Programming

Learning objectives

  • Create DataFrames and read CSV data
  • Select, filter and sort rows and columns
  • Group, aggregate and pivot data

Definition

pandas is a library for working with labelled, tabular data. A DataFrame is a table of rows and named columns (each a Series), with powerful tools for loading, cleaning, filtering, grouping and summarising data.

Introduction

Spreadsheets are great until the data has 500,000 rows or the same steps must be repeated every week. pandas does spreadsheet work in code — repeatable and fast.

Why it matters

pandas is the standard tool for data analysis in Python, used in business reporting, science, finance and machine-learning preparation.

Detailed explanation

Install with python -m pip install pandas; import it as pd.

A Series is a labelled one-dimensional column; a DataFrame is a two-dimensional table of Series sharing an index.

Create DataFrames from dictionaries of lists or load them with pd.read_csv, read_excel, read_json and many more.

df["col"] selects a column; df[["a", "b"]] several. df[df["marks"] > 80] filters rows with a boolean condition; combine conditions with & and |.

sort_values orders rows; head and tail show the first or last rows; describe summarises numeric columns.

groupby("col")["value"].agg(["sum", "mean"]) aggregates per group; pivot_table reshapes data into a cross-tabulation.

Operations return new DataFrames by default, so assign the result (df = df.dropna()) to keep it.

Columns have dtypes like NumPy arrays; parse_dates turns text dates into real datetimes for date arithmetic.

Syntax

Python
import pandas as pd
df = pd.read_csv("sales.csv")
df[df["amount"] > 100]
df.groupby("region")["amount"].sum()
df.sort_values("amount", ascending=False)
  • DataFrame = table; Series = column.
  • Filter with boolean conditions.
  • groupby for summaries.

Code examples

A first DataFrame

Python
import pandas as pd
df = pd.DataFrame({"name": ["Asha", "Ravi", "Meera"], "city": ["Pune", "Delhi", "Pune"], "marks": [91, 78, 85]})
print(df)
print(df["marks"].mean(), len(df))
Output
    name   city  marks
0   Asha   Pune     91
1   Ravi  Delhi     78
2  Meera   Pune     85
84.66666666666667 3

Requires pandas.

Filtering, sorting and grouping

Python
import pandas as pd
df = pd.DataFrame({"name": ["Asha", "Ravi", "Meera"], "city": ["Pune", "Delhi", "Pune"], "marks": [91, 78, 85]})
print(df[df["marks"] > 80][["name", "marks"]])
print(df.sort_values("marks", ascending=False)["name"].tolist())
print(df.groupby("city")["marks"].mean().to_dict())
Output
    name  marks
0   Asha     91
2  Meera     85
['Asha', 'Meera', 'Ravi']
{'Delhi': 78.0, 'Pune': 88.0}

Requires pandas.

More examples

Summarising sales data

Python
import io
import pandas as pd
csv_text = "date,region,amount\n2026-11-01,North,120\n2026-11-01,South,300\n2026-11-02,North,250\n2026-11-02,South,80\n2026-11-03,North,60\n"
sales = pd.read_csv(io.StringIO(csv_text), parse_dates=["date"])
print(sales.groupby("region")["amount"].agg(["sum", "mean", "count"]))
daily = sales.pivot_table(index="date", columns="region", values="amount", aggfunc="sum", fill_value=0)
print(daily)
print(sales["amount"].describe()[["mean", "max"]].round(1).to_dict())
Output
        sum        mean  count
region                        
North   430  143.333333      3
South   380  190.000000      2
region      North  South
date                    
2026-11-01    120    300
2026-11-02    250     80
2026-11-03     60      0
{'mean': 162.0, 'max': 300.0}

Requires pandas. Reading from io.StringIO works exactly like reading a CSV file.

Step-by-step explanation

  • read_csv parses the text and converts the date column into real dates.
  • groupby with agg computes several statistics per region in one call.
  • pivot_table turns regions into columns and dates into rows, filling missing combinations with 0.

Expected output

Running “Summarising sales data” prints exactly:

TextOutput
sum mean count
region
North 430 143.333333 3
South 380 190.000000 2
region North South
date
2026-11-01 120 300
2026-11-02 250 80
2026-11-03 60 0
{'mean': 162.0, 'max': 300.0}

Practical applications

  • Weekly sales and finance reports.
  • Cleaning survey data before analysis.

Best practices

  • Load data with read_csv and explicit options.
  • Filter with boolean conditions, not loops.
  • Use groupby and pivot_table for summaries.

Common mistakes

Forgetting to assign results

Avoid

df.dropna()
print(df) # still has missing values

Prefer

df = df.dropna()

Most pandas methods return a new DataFrame.

Python and/or in filters

Avoid

df[df.a > 1 and df.b < 5]

Prefer

df[(df.a > 1) & (df.b < 5)]

Element-wise conditions need & and |, with parentheses.

Important notes

  • Jupyter notebooks display DataFrames as formatted tables, which makes exploring data easier.

Key takeaways

  • DataFrames hold tables; Series hold columns.
  • Select, filter and sort with concise expressions.
  • groupby, agg and pivot_table summarise data.

Try it yourself

  1. 1
    Load a CSV of expenses and show the total per category, largest first.
  2. 2
    Find the student with the highest average from a DataFrame of marks.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

Test yourself across the whole course in the Python practice bank.