Summarizing Dates in Pandas – GroupBy, Resample & Date Features in Python 2026

Data Manipulation Mar 18, 2026

Summarizing Dates in Pandas – GroupBy, Resample & Date Features in Python 2026

Summarizing data by dates (daily, weekly, monthly, quarterly, yearly) is one of the most common tasks in data manipulation. In 2026, Pandas provides powerful and clean ways to aggregate time-based data using .dt accessors, groupby(), and resample().

TL;DR — Best Methods for Date Summarization

  • .dt accessor for extracting components
  • groupby() with date parts (year, month, week)
  • resample() for time-series aggregation
  • Grouper() for flexible grouping

1. Extracting Date Components

import pandas as pd

# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
    "order_date": pd.date_range("2025-10-01", periods=n, freq="3D"),
    "customer_id": rng.integers(101, 121, n),
    "customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
    "product_id": rng.integers(1, 9, n),
    "region": rng.choice(["North", "South", "East", "West"], n),
    "category": rng.choice(["Electronics", "Books", "Home"], n),
    "payment_method": rng.choice(["card", "cash", "wallet"], n),
    "segment": rng.choice(["consumer", "business"], n),
    "quantity": rng.integers(1, 6, n),
    "amount": rng.uniform(50, 2500, n).round(2),
}).assign(
    ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
    status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)

df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])

df["year"] = df["order_date"].dt.year
df["month"] = df["order_date"].dt.month
df["month_name"] = df["order_date"].dt.month_name()
df["week"] = df["order_date"].dt.isocalendar().week
df["weekday"] = df["order_date"].dt.day_name()
df["quarter"] = df["order_date"].dt.quarter

2. Grouping & Summarizing by Date

# Monthly sales summary
monthly = (
    df
    .groupby(["region", df["order_date"].dt.to_period("M")])
    .agg({
        "amount": ["sum", "mean", "count"],
        "customer_id": "nunique"
    })
    .round(2)
)

# Weekly summary using Grouper
weekly = df.groupby(pd.Grouper(key="order_date", freq="W-MON")).agg({
    "amount": "sum",
    "quantity": "sum"
})

3. Using resample() for Time Series

# Set order_date as index for resampling
df = df.set_index("order_date")

daily_sales = df["amount"].resample("D").sum()
weekly_sales = df["amount"].resample("W").sum()
monthly_sales = df["amount"].resample("ME")   # "ME" = month end ("M" was removed in pandas 3).sum()

print(monthly_sales)

4. Best Practices in 2026

  • Use parse_dates when reading CSV to avoid string-to-datetime conversion later
  • Prefer pd.Grouper(freq=...) or .dt.to_period() for clean grouping
  • Use resample() when your DataFrame has a datetime index
  • Always name your aggregated columns for better readability
  • Combine with .round() and .reset_index() for clean output

How pandas Thinks About Dates

Date summaries answer questions such as "how much did we sell each month?" or "which weekday is busiest?". pandas offers two routes. With groupby() you first extract a component, for example df["order_date"].dt.month, and group on it; the result ignores gaps and treats every January the same, whatever the year. With resample() the dates become a continuous calendar: every period between the first and last date appears, even when it has no rows, which is what you want for time series charts.

Both routes need a real datetime column. If dt raises an error, the column is still text, so convert it with pd.to_datetime() or parse_dates when reading the file.

Worked Example: Weekly and Weekday Totals

This small, self-contained example builds daily orders and summarises them in both ways.

import pandas as pd

orders = pd.DataFrame({
    "order_date": pd.date_range("2026-03-02", periods=10, freq="D"),
    "amount": [120, 80, 0, 50, 200, 30, 90, 110, 60, 40],
})

weekly = orders.resample("W-SUN", on="order_date")["amount"].sum()
print(weekly)
# 2026-03-08    570
# 2026-03-15    210

by_day = orders.groupby(orders["order_date"].dt.day_name())["amount"].sum()
print(by_day.sort_values(ascending=False).head(3))

The weekly result follows the calendar, while the weekday result mixes both weeks together. Choose the one that matches the question you are answering.

Common Mistakes

  • Grouping on text dates: "2026-03-02" sorts as a string, not a date; convert first
  • Using the month number alone: January 2025 and January 2026 fall into one group; group on dt.to_period("M") instead
  • Old frequency aliases: pandas 3 needs "ME" and "h", not "M" and "H"
  • Forgetting empty periods: groupby() skips them, resample() shows them as 0 or NaN

Quick Summary

  • Convert to datetime first, then use the dt accessor
  • groupby() for repeating patterns, resample() for a timeline
  • Use to_period("M") to keep the year in monthly groups

Conclusion

Summarizing dates effectively is a core skill in data manipulation. In 2026, combining Pandas .dt accessors, groupby() with Grouper, and resample() gives you full control over time-based analysis. These techniques help you turn raw timestamps into meaningful business insights quickly and cleanly.

Next steps:

  • Take one of your datasets with date columns and create monthly/weekly summaries using the methods above

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices