Example 47
advanced
47
DataFrame

DataFrame IO & Styling

A practical DataFrame operations example for the v1.0.0 polish layer: JSON/XLSX/Parquet round-trips, datetime parsing, styling, and pandas-like plotting accessors. This example uses deepbox/dataframe and focuses on DataFrame, date_range, to_datetime, readXlsx, writeXlsx, readParquet, writeParquet, style, plot.

Deepbox Modules Used

deepbox/dataframe

What You Will Learn

  • Use deepbox/dataframe for DataFrame, date_range, to_datetime, readXlsx, writeXlsx, readParquet, writeParquet, style, plot.
  • A practical DataFrame operations example for the v1.0.0 polish layer: JSON/XLSX/Parquet round-trips, datetime parsing, styling, and pandas-like plotting accessors.

Source Files

index.ts
1/**2 * Example 47: DataFrame IO & Styling3 *4 * Demonstrates v1.0.0 DataFrame operational polish: JSON/XLSX/Parquet round-trips,5 * string/date helpers, style rendering, and pandas-like plotting accessors.6 */78import { mkdir, writeFile } from "node:fs/promises";9import {10  DataFrame,11  date_range,12  readParquet,13  readXlsx,14  to_datetime,15  writeParquet,16  writeXlsx,17} from "deepbox/dataframe";1819const OUTPUT_DIR = "docs/examples/47-dataframe-io-styling/output";2021console.log("=".repeat(60));22console.log("Example 47: DataFrame IO & Styling");23console.log("=".repeat(60));2425await mkdir(OUTPUT_DIR, { recursive: true });2627const orderDates = date_range("2026-03-01", 6, "D");28const orderDateStrings = Array.from(orderDates.data, (value) =>29  value instanceof Date ? value.toISOString().slice(0, 10) : ""30);3132const rows = [33  {34    orderDate: orderDateStrings[0] ?? "2026-03-01",35    region: "GCC",36    segment: "Enterprise",37    revenue: 180_000,38    supportTickets: 12,39    activeCampaign: true,40  },41  {42    orderDate: orderDateStrings[1] ?? "2026-03-02",43    region: "North Africa",44    segment: "SMB",45    revenue: 124_000,46    supportTickets: 21,47    activeCampaign: false,48  },49  {50    orderDate: orderDateStrings[2] ?? "2026-03-03",51    region: "GCC",52    segment: "Mid-Market",53    revenue: 155_000,54    supportTickets: 16,55    activeCampaign: true,56  },57  {58    orderDate: orderDateStrings[3] ?? "2026-03-04",59    region: "Levant",60    segment: "Enterprise",61    revenue: 212_000,62    supportTickets: 9,63    activeCampaign: true,64  },65  {66    orderDate: orderDateStrings[4] ?? "2026-03-05",67    region: "North Africa",68    segment: "Enterprise",69    revenue: 167_000,70    supportTickets: 13,71    activeCampaign: false,72  },73  {74    orderDate: orderDateStrings[5] ?? "2026-03-06",75    region: "Levant",76    segment: "SMB",77    revenue: 98_000,78    supportTickets: 24,79    activeCampaign: false,80  },81];8283const df = new DataFrame({84  orderDate: rows.map((row) => row.orderDate),85  region: rows.map((row) => row.region),86  segment: rows.map((row) => row.segment),87  revenue: rows.map((row) => row.revenue),88  supportTickets: rows.map((row) => row.supportTickets),89  activeCampaign: rows.map((row) => row.activeCampaign),90});9192// ============================================================================93// Part 1: CSV ingest + datetime helpers94// ============================================================================95console.log("\n📥 Part 1: CSV + Date Helpers");96console.log("-".repeat(60));9798const csvRoundTrip = DataFrame.fromCsvString(df.toCsvString());99const parsedDates = to_datetime(rows.map((row) => row.orderDate));100101console.log(`Round-trip CSV shape: ${csvRoundTrip.shape[0]} rows × ${csvRoundTrip.shape[1]} cols`);102console.log(103  `Parsed weekday numbers: ${Array.from(parsedDates.dt.dayofweek().data, (value) => String(value)).join(", ")}`104);105106// ============================================================================107// Part 2: JSON, XLSX, and Parquet round-trips108// ============================================================================109console.log("\n🗃️  Part 2: JSON / XLSX / Parquet");110console.log("-".repeat(60));111112const jsonPath = `${OUTPUT_DIR}/regional-sales.json`;113await df.toJson(jsonPath);114const jsonReloaded = await DataFrame.readJson(jsonPath);115116const xlsxBytes = writeXlsx(df.columns, rows, { sheetName: "RegionalSales" });117const xlsxPath = `${OUTPUT_DIR}/regional-sales.xlsx`;118await writeFile(xlsxPath, xlsxBytes);119const xlsxReloaded = readXlsx(xlsxBytes);120121const parquetBytes = writeParquet(df.columns, rows);122const parquetPath = `${OUTPUT_DIR}/regional-sales.parquet`;123await writeFile(parquetPath, parquetBytes);124const parquetReloaded = readParquet(parquetBytes);125126console.log(`JSON rows reloaded:    ${jsonReloaded.shape[0]}`);127console.log(`XLSX rows reloaded:    ${xlsxReloaded.data.length}`);128console.log(`Parquet rows reloaded: ${parquetReloaded.data.length}`);129130// ============================================================================131// Part 3: String accessor + styling132// ============================================================================133console.log("\n🎨 Part 3: String Accessor + Styling");134console.log("-".repeat(60));135136const regionSeries = df.get("region");137console.log(`Upper-case regions: ${regionSeries.str.upper().toString()}`);138139const styledHtml = df.style140  .setCaption("Daily Revenue Operations Snapshot")141  .highlight_max({ backgroundColor: "#dcfce7", fontWeight: "bold" })142  .background_gradient("#fff7ed", "#fb923c")143  .format("revenue", (value) => `$${Number(value).toLocaleString("en-US")}`)144  .format("supportTickets", (value) => `${value} tickets`)145  .toHTML();146147const ansiTable = df.style148  .highlight_min({ backgroundColor: "#fee2e2" })149  .format("revenue", (value) => `$${Number(value).toLocaleString("en-US")}`)150  .toANSI();151152const htmlPath = `${OUTPUT_DIR}/styled-sales-report.html`;153const ansiPath = `${OUTPUT_DIR}/styled-sales-report.txt`;154await writeFile(htmlPath, styledHtml, "utf-8");155await writeFile(ansiPath, ansiTable, "utf-8");156157console.log(`Styled HTML report: ${htmlPath}`);158console.log(`Styled ANSI table:  ${ansiPath}`);159160// ============================================================================161// Part 4: Plot accessor162// ============================================================================163console.log("\n📈 Part 4: Plot Accessor");164console.log("-".repeat(60));165166const trend = new DataFrame({167  day: [1, 2, 3, 4, 5, 6],168  revenue: rows.map((row) => row.revenue),169  supportTickets: rows.map((row) => row.supportTickets),170});171172const trendFigure = trend.plot.line({173  x: "day",174  y: ["revenue", "supportTickets"],175  title: "Revenue vs Support Load",176  figsize: [800, 480],177});178179const svgPath = `${OUTPUT_DIR}/revenue-support-trend.svg`;180await writeFile(svgPath, trendFigure.renderSVG().svg, "utf-8");181182console.log(`Plot saved to: ${svgPath}`);183184// ============================================================================185// Summary186// ============================================================================187console.log("\n💡 Key Takeaways");188console.log("-".repeat(60));189console.log("• DataFrame supports JSON file IO directly and zero-dependency XLSX/Parquet codecs");190console.log("• Date helpers and string accessors make operational reports easier to clean");191console.log("• df.style can emit HTML or ANSI-ready reports for notebooks and terminals");192console.log("• df.plot offers pandas-like plotting without leaving the Deepbox stack");193194console.log("\n✅ DataFrame IO & Styling Example Complete!");195console.log("=".repeat(60));196

Console Output

$ npx tsx 47-dataframe-io-styling/index.ts
JSON, XLSX, and Parquet example files in `output/`
Styled HTML and ANSI reports
SVG trend chart rendered with `df.plot.line()`