python 27 lines · 1 tab

GroupBy aggregations and pivot tables for business reporting

1 tab
import pandas as pd

df = pd.read_parquet('events.parquet')
df['event_date'] = pd.to_datetime(df['event_date'])
df['month'] = df['event_date'].dt.to_period('M').astype(str)

channel_summary = (
    df.groupby(['month', 'acquisition_channel'], as_index=False)
    .agg(
        sessions=('session_id', 'nunique'),
        users=('user_id', 'nunique'),
        revenue=('revenue', 'sum'),
        avg_order_value=('revenue', 'mean'),
    )
)

revenue_matrix = pd.pivot_table(
    channel_summary,
    index='month',
    columns='acquisition_channel',
    values='revenue',
    fill_value=0,
    aggfunc='sum',
)

print(channel_summary.head())
print(revenue_matrix.tail())
1 file · python Explain with highlit

I reach for groupby when I need trustworthy aggregates that can power dashboards or analytical reports. Clear aggregation naming matters because these outputs frequently get joined back into feature tables or exported to BI systems. pivot_table is useful when stakeholders want category x time summaries without manual spreadsheet work.


Related snips

ruby
class ReportQuery
  SQL = <<~SQL.freeze
    SELECT date_trunc('day', events.created_at) AS day,
           count(*) AS total,
           count(*) FILTER (WHERE events.kind = 'purchase') AS purchases
    FROM events

Safe Raw SQL with exec_query + Binds

rails activerecord sql
by codesnips 2 tabs
python
import pandas as pd

df = pd.read_csv('customers.csv')

df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_', regex=False)

Cleaning missing values and normalizing messy CSV exports

pandas data-cleaning missing-values
by Dr. Elena Vasquez 1 tab
python
import pandas as pd

df = pd.read_csv('traffic.csv', parse_dates=['timestamp'])
df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True)
df = df.set_index('timestamp').sort_index()

Time series resampling and rolling windows in pandas

pandas time-series resampling
by Dr. Elena Vasquez 1 tab
python
from django.db.models import F, Window
from django.db.models.functions import RowNumber, Rank, DenseRank
from products.models import Sale


def get_sales_with_ranking():

Django ORM window functions for analytics

django python database
by Priya Sharma 1 tab
ruby
class ShardedCounter
  SHARDS = 16
  SNAPSHOT_TTL = 10 # seconds

  def initialize(name, redis: REDIS)
    @name = name

Lock-Free Read Pattern for Hot Counters (Approximate)

rails redis performance
by codesnips 3 tabs
ruby
class CspReportsController < ActionController::API
  def create
    Rails.logger.warn({
      event: 'csp_report',
      report: params.to_unsafe_h,
      ip: request.remote_ip,

CSP report endpoint for monitoring attempted browser policy violations

csp reporting browser-security
by Kai Nakamura 1 tab

Share this code

Here's the card — post it anywhere.

GroupBy aggregations and pivot tables for business reporting — share card
Link copied