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.
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.
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.
| order_id | region | producto | ventas |
|---|---|---|---|
| 1 | South | Laptop | 1500 |
| 2 | North | Mouse | 35 |
| 3 | South | Server | 8500 |
| 4 | West | Monitor | 320 |
| 5 | North | Workstation | 2200 |
import polars as pl
df = (
pl.scan_csv("dataset_gigante_2026.csv")
.filter(pl.col("ventas") > 1000)
.collect()
)# ==========================================================
# 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}")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 │ └────────┴────────────────────┴────────────────┴────────────────┘
| region | cantidad_registros | ventas_totales | venta_promedio |
|---|---|---|---|
| South | 2 | 10000 | 5000.00 |
| North | 1 | 2200 | 2200.00 |
| East | 1 | 1800 | 1800.00 |
# 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)
scan_csv para datasets grandes.scan_csv for large datasets.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.