Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Python Pandas for Data Manipulation and Analysis

Python’s pandas library provides a practical way to work with structured data. It turns rows and columns into labelled objects that can be filtered, joined, summarised and reshaped with relatively little code. For many data tasks, pandas sits between raw files and statistical or machine learning tools.

A typical workflow starts by reading a CSV, checking its columns, cleaning missing values, and producing summaries that answer a specific question. The same approach works for a small spreadsheet of household expenses, a large export from a business system, or public data from an Australian council.

The examples below focus on reliable habits rather than one-off tricks. They cover DataFrames, Series, indexing, data types, grouping, joins and reshaping, with complexity and performance considerations where they matter.

Understanding DataFrames And Series

A pandas DataFrame is a two-dimensional structure with labelled rows and columns. A Series is a single labelled column. You can create both directly:

import pandas as pd

sales = pd.DataFrame({
    "product": ["Tea", "Coffee", "Tea"],
    "store": ["Sydney", "Melbourne", "Sydney"],
    "units": [12, 8, 15],
    "price": [4.50, 5.00, 4.50]
})

sales["revenue"] = sales["units"] * sales["price"]

The expression sales["units"] returns a Series, while sales remains a DataFrame. Labels make operations expressive, and pandas aligns values by index during many calculations. This is convenient, though it means an unexpected index can produce missing values when objects are combined.

Useful first checks include sales.head(), sales.shape, sales.columns, sales.dtypes and sales.describe(). Calling sales.info() is especially helpful because it shows non-null counts and memory usage. These checks reveal whether a column was imported as a number, text or an unsuitable mixed type.

Reading Files And Inspecting Data

CSV files are common, so the basic import is:

orders = pd.read_csv("orders.csv")

For Australian data, dates may appear as 31/03/2025, and a file may use semicolons or contain dollar symbols. Specify these details rather than relying on automatic guessing:

orders = pd.read_csv(
    "orders.csv",
    parse_dates=["order_date"],
    dayfirst=True
)

orders["amount"] = (
    orders["amount"]
    .str.replace("$", "", regex=False)
    .str.replace(",", "", regex=False)
    .astype(float)
)

Excel workbooks use pd.read_excel(), while JSON data can be loaded with pd.read_json(). Large files may require usecols to select relevant columns or chunksize to process rows in batches. This reduces memory pressure when a national retail export is too large to fit comfortably in RAM.

Data profiling should happen before analysis. Look for duplicated column names, impossible dates, negative quantities, inconsistent capitalisation and codes with leading zeroes. A postcode is usually an identifier, not a numeric measurement, so it should often remain a string.

Selecting Rows And Columns

Column selection is straightforward:

selected = orders[["order_id", "order_date", "amount"]]

For row filtering, use Boolean expressions. Parentheses are important when combining conditions:

large_orders = orders[
    (orders["amount"] >= 100) &
    (orders["status"] == "complete")
]

The .loc accessor handles label-based selection and is clear when both rows and columns are involved:

result = orders.loc[
    orders["state"].isin(["NSW", "VIC"]),
    ["order_id", "amount", "state"]
]

Use .iloc when selecting by integer position, such as orders.iloc[:10, :4]. Avoid chained assignment such as orders[orders["amount"] > 100]["flag"] = True; it can modify a temporary object rather than the original DataFrame. Prefer .loc:

orders.loc[orders["amount"] > 100, "flag"] = True

Filtering is often the first place where a business definition becomes code. “Victorian customers” might mean a shipping state, billing state or registered address. A clean analysis states which field represents the concept.

Cleaning Missing And Inconsistent Values

Missing data is represented by values such as NaN or NaT. Count it with:

orders.isna().sum()

You can remove incomplete rows with dropna(), fill values with fillna(), or preserve missingness for later modelling. The correct choice depends on meaning. A missing discount may reasonably become zero, while a missing customer identifier should not silently receive a made-up value.

orders["discount"] = orders["discount"].fillna(0)
orders = orders.dropna(subset=["order_id", "order_date"])

Text fields benefit from normalisation:

orders["state"] = (
    orders["state"]
    .str.strip()
    .str.upper()
)

orders["customer_name"] = orders["customer_name"].str.title()

Be careful with .str.title() for names such as “McDonald” or “O’Neill”, where automatic formatting may be imperfect. Dates can be converted safely with pd.to_datetime(..., errors="coerce"), turning invalid entries into missing timestamps that can then be investigated.

Practical Data Quality Checks

These checks matter in local datasets too. A council dataset might contain suburbs with different spellings, while Bureau of Meteorology observations may use station codes rather than suburb names. Cleaning should preserve the source meaning instead of making every value look uniform.

Summarising With GroupBy

The groupby operation divides data into groups, applies calculations and combines the results. For example:

summary = (
    orders.groupby("state", as_index=False)
    .agg(
        orders=("order_id", "nunique"),
        revenue=("amount", "sum"),
        average_order=("amount", "mean")
    )
    .sort_values("revenue", ascending=False)
)

This produces one row per state. Multiple grouping columns support more detailed analysis:

by_store = (
    sales.groupby(["store", "product"], as_index=False)
    .agg(
        units=("units", "sum"),
        revenue=("revenue", "sum")
    )
)

transform() is useful when you need a group statistic repeated beside every original row. To calculate each order’s share of its state’s revenue:

orders["state_total"] = orders.groupby("state")["amount"].transform("sum")
orders["state_share"] = orders["amount"] / orders["state_total"]

Grouping is also a natural way to examine seasonal or regional patterns, such as comparing weekly sales in Brisbane with Melbourne. When ordering results, remember that calendar weeks, financial years and Australian tax periods may not align with a simple month number.

For algorithmic context, sorting a result has a cost. The sorting complexity guide explains why ordering n records is generally more expensive than a direct lookup, which becomes relevant when repeatedly sorting a large DataFrame.

Joining And Reshaping Tables

Real datasets are often split across tables. Use merge() when two DataFrames share a key:

customers = pd.DataFrame({
    "customer_id": [1, 2],
    "segment": ["Home", "Business"]
})

orders = orders.merge(
    customers,
    on="customer_id",
    how="left",
    validate="many_to_one"
)

The validate argument can catch an unexpected relationship. A left join keeps every order, while an inner join keeps only rows with a matching customer. Before joining, inspect key types; integer customer IDs will not match string IDs reliably.

Concatenation stacks compatible DataFrames:

all_orders = pd.concat([january, february], ignore_index=True)

Use pivot_table() to turn long data into a summary matrix:

monthly = pd.pivot_table(
    orders,
    values="amount",
    index="state",
    columns="month",
    aggfunc="sum",
    fill_value=0
)

melt() performs the reverse transformation, converting columns into rows. Long format is generally convenient for plotting and grouped calculations, while wide format is useful for reports. A dataset from Australian supermarkets, for example, might store each month as a separate column in a spreadsheet but need to be melted before visualisation.

Working With Time And Performance

Datetime columns unlock operations such as extracting a year, resampling by month and calculating elapsed time:

orders["year"] = orders["order_date"].dt.year
orders["month"] = orders["order_date"].dt.to_period("M")

monthly_revenue = (
    orders.groupby("month")["amount"]
    .sum()
)

Timezone handling deserves care across Australia. Sydney and Melbourne observe daylight saving, while Brisbane does not, and Perth uses another local time. If events arrive with timezone information, convert them deliberately rather than comparing naive timestamps as if every record used the same clock.

For performance, prefer vectorised expressions over Python loops:

orders["net_amount"] = orders["amount"] - orders["discount"]

Convert repeated text categories to the category dtype when appropriate, and select only the columns needed for an operation. For huge files, process chunks and write intermediate summaries instead of keeping every raw row in memory. Use memory_usage(deep=True) to identify expensive object columns.

Pandas is excellent for data preparation, but it is not a substitute for a database when filtering billions of rows. Push large queries into SQL where possible, then use pandas for analysis and modelling. After preparing features, a classification workflow may continue into scikit-learn; an explanation of logistic regression shows how tabular variables can support binary predictions.

Choosing The Right Operation

The following comparison helps match common pandas operations to their purpose and typical behaviour. Complexity depends on data layout, implementation details and the number of groups, so the figures are useful guidelines rather than guarantees.

Operation Typical purpose Example General performance note
Column selection Choose fields df[["name", "amount"]] Usually proportional to selected data
Boolean filtering Keep matching rows df[df["amount"] > 100] Scans the relevant rows
sort_values Order records df.sort_values("amount") Commonly around O(n log n)
groupby().agg() Calculate grouped summaries df.groupby("state")["amount"].sum() Often close to linear, plus grouping overhead
merge Combine related tables left.merge(right, on="id") Depends on keys, sizes and join strategy
drop_duplicates Remove repeated records df.drop_duplicates("id") Usually near linear with hashing
pivot_table Create cross-tabulated summaries pd.pivot_table(...) Depends on row count and group combinations

A sound pandas workflow is therefore a sequence of small, inspectable transformations: load the data, verify its shape, clean types and missing values, filter with explicit conditions, summarise, join only when keys are understood, and export a result whose meaning is clear. That method scales from a quick arvo analysis of local sales to a reproducible report built from public Australian datasets.