Python Advanced Series

6. Procesar archivos masivos sin RAM

6. Process Massive Files Without RAM

Reemplaza Pandas por Polars para procesar datasets de 20GB+ usando evaluación perezosa y procesamiento multihilo.

Replace Pandas with Polars to process 20GB+ datasets using lazy evaluation and multithreaded processing.

⚠️ Advertencia de ciberseguridad, datos y producción ⚠️ Cybersecurity, data, and production warning

Este ejercicio es solo para aprendizaje y pruebas. No ejecutes modelos contra datos reales, sensibles, financieros, médicos, personales o ambientes de producción sin autorización, respaldos, pruebas previas, permisos mínimos, control de cambios, revisión humana y cumplimiento de los protocolos de ciberseguridad y privacidad de tu organización.

This exercise is for learning and testing only. Do not run models against real, sensitive, financial, medical, personal, or production data without authorization, backups, prior testing, least-privilege permissions, change control, human review, and compliance with your organization's cybersecurity and privacy protocols.

Objetivo del ejercicio

Exercise objective

Usar Polars LazyFrame para leer, filtrar, agrupar y exportar grandes archivos CSV sin cargar todo el dataset en memoria desde el inicio. El proceso se optimiza antes de ejecutarse.

Use Polars LazyFrame to read, filter, group, and export large CSV files without loading the full dataset into memory up front. The process is optimized before execution.

Datos sintéticos

Synthetic data

order_idregionproductoventas
1SouthLaptop1500
2NorthMouse35
3SouthServer8500
4WestMonitor320
5NorthWorkstation2200

Ejemplo base

Base example

import polars as pl

df = (
    pl.scan_csv("dataset_gigante_2026.csv")
      .filter(pl.col("ventas") > 1000)
      .collect()
)

Script completo

Complete script

# ==========================================================
# Python Advanced Topic 06
# Process Massive Files Without RAM using Polars
# ==========================================================

import polars as pl

input_file = "dataset_gigante_2026.csv"
output_file = "ventas_filtradas_resumen.csv"

# 1. Create a lazy scan of the CSV file.
# The data is not fully loaded yet.
lazy_df = pl.scan_csv(input_file)

# 2. Build an optimized query plan
resultado = (
    lazy_df
    .filter(pl.col("ventas") > 1000)
    .group_by("region")
    .agg([
        pl.len().alias("cantidad_registros"),
        pl.sum("ventas").alias("ventas_totales"),
        pl.mean("ventas").round(2).alias("venta_promedio")
    ])
    .sort("ventas_totales", descending=True)
)

# 3. Execute the plan only now
final_df = resultado.collect()

# 4. Export result
final_df.write_csv(output_file)

print(final_df)
print(f"Report created: {output_file}")

Salida esperada en consola

Expected console output

shape: (3, 4)
┌────────┬────────────────────┬────────────────┬────────────────┐
│ region ┆ cantidad_registros ┆ ventas_totales ┆ venta_promedio │
│ ---    ┆ ---                ┆ ---            ┆ ---            │
│ str    ┆ u32                ┆ i64            ┆ f64            │
╞════════╪════════════════════╪════════════════╪════════════════╡
│ South  ┆ 2                  ┆ 10000          ┆ 5000.0         │
│ North  ┆ 1                  ┆ 2200           ┆ 2200.0         │
│ East   ┆ 1                  ┆ 1800           ┆ 1800.0         │
└────────┴────────────────────┴────────────────┴────────────────┘

Reporte CSV generado

Generated CSV report

regioncantidad_registrosventas_totalesventa_promedio
South2100005000.00
North122002200.00
East118001800.00

Validación rápida

Quick validation

# Check schema without loading the full file
print(pl.scan_csv(input_file).collect_schema())

# Preview only a few rows
preview = pl.scan_csv(input_file).head(5).collect()
print(preview)

Aplicaciones reales

Real-world applications

  • Procesar logs masivos.
  • Filtrar millones de transacciones.
  • Preparar archivos grandes para Power BI o SQL.
  • Crear resúmenes sin abrir Excel.
  • Process massive logs.
  • Filter millions of transactions.
  • Prepare large files for Power BI or SQL.
  • Create summaries without opening Excel.

Recomendaciones

Recommendations

  • Usar scan_csv para datasets grandes.
  • Filtrar temprano para reducir volumen.
  • Exportar resultados agregados, no todo el detalle.
  • Validar tipos de columnas antes de procesar.
  • Use scan_csv for large datasets.
  • Filter early to reduce volume.
  • Export aggregated results, not all detail.
  • Validate column types before processing.

Valor del tópico

Topic value

Este patrón permite trabajar con archivos que normalmente romperían Excel o consumirían demasiada memoria en Pandas. Es una puerta práctica hacia procesos de Big Data locales y eficientes.

This pattern makes it possible to work with files that would normally break Excel or consume too much memory in Pandas. It is a practical gateway to local and efficient Big Data workflows.