Example 05
beginner
05
DataFrame
GroupBy
Aggregation

DataFrame GroupBy & Aggregation

GroupBy is one of the most powerful DataFrame operations. This example demonstrates splitting a dataset into groups based on a column value, then applying aggregate functions (mean, sum, count, min, max) to each group independently. You create an employee DataFrame, group by department, and compute average salary and maximum experience per department. This is the Deepbox equivalent of SQL's GROUP BY('col').agg(). The result is a new DataFrame with one row per group and the aggregated values as columns.

Deepbox Modules Used

deepbox/dataframe

What You Will Learn

  • Group rows by column values with .groupBy()
  • Apply aggregate functions: mean, sum, count, min, max
  • The result is a new DataFrame with one row per group
  • Equivalent to SQL GROUP BY ... agg()

Source Code

05-dataframe-groupby/index.ts
1import { DataFrame } from "deepbox/dataframe";23console.log("=== DataFrame GroupBy ===\n");45const df = new DataFrame({6  dept: ["Eng", "Sales", "Eng", "HR", "Sales", "Eng", "HR", "Sales"],7  salary: [90000, 60000, 95000, 50000, 65000, 100000, 55000, 70000],8  years: [5, 3, 8, 2, 4, 10, 3, 6],9});1011console.log("Original data:");12console.log(df.toString());1314// Group by department, aggregate salary and years15const grouped = df.groupBy("dept").agg({16  salary: "mean",17  years: "max",18});1920console.log("\nGrouped by department:");21console.log(grouped.toString());2223// Count per group24const counts = df.groupBy("dept").agg({25  salary: "count",26});27console.log("\nEmployee count per dept:");28console.log(counts.toString());

Console Output

$ npx tsx 05-dataframe-groupby/index.ts
=== DataFrame GroupBy ===

Original data:
┌───────┬────────┬───────┐
│ dept  │ salary │ years │
├───────┼────────┼───────┤
│ Eng   │  90000 │     5 │
│ Sales │  60000 │     3 │
│ Eng   │  95000 │     8 │
│ HR    │  50000 │     2 │
│ Sales │  65000 │     4 │
│ Eng   │ 100000 │    10 │
│ HR    │  55000 │     3 │
│ Sales │  70000 │     6 │
└───────┴────────┴───────┘

Grouped by department:
┌───────┬──────────┬───────┐
│ dept  │  salary  │ years │
├───────┼──────────┼───────┤
│ Eng   │  95000.0 │    10 │
│ Sales │  65000.0 │     6 │
│ HR    │  52500.0 │     3 │
└───────┴──────────┴───────┘