Python Training · Topic 1

Normalizar columnas inconsistentes

Un ejercicio práctico para convertir encabezados desordenados en nombres estándar listos para análisis, validación o carga.

Normalize inconsistent columns

A hands-on exercise to convert messy headers into standard names ready for analysis, validation, or upload.

⚠️ Advertencia crítica antes de correr cualquier script

No ejecutes scripts de Python contra archivos oficiales, bases de datos reales, carpetas institucionales, SQL Server, Access, APIs internas o datasets sensibles sin autorización formal.

Python puede transformar miles o millones de filas en segundos. Un cambio mal probado puede sobrescribir archivos, alterar columnas críticas, crear resultados incorrectos, exponer datos sensibles o afectar procesos de BI, auditoría o producción.

Regla obligatoria del training: primero se trabaja con data sintética, luego con una copia controlada, después se valida el resultado, y solo entonces se considera usar datos reales siguiendo permisos, backup, change control, data governance y protocolos de ciberseguridad.

  • Permisos: usa solamente archivos y fuentes donde tengas autorización explícita.
  • Backups: nunca sobrescribas data original sin una copia recuperable.
  • Data governance: respeta privacidad, controles de acceso y clasificación de datos.
  • Producción: nunca conectes scripts a fuentes reales sin revisión, aprobación y plan de reversa.

⚠️ Critical warning before running any script

Do not run Python scripts against official files, real databases, institutional folders, SQL Server, Access, internal APIs, or sensitive datasets without formal authorization.

Python can transform thousands or millions of rows in seconds. A poorly tested change can overwrite files, alter critical columns, create incorrect outputs, expose sensitive data, or affect BI, audit, or production processes.

Mandatory training rule: start with synthetic data, then use a controlled copy, validate the result, and only then consider real data while following permissions, backups, change control, data governance, and cybersecurity protocols.

  • Permissions: use only files and sources where you have explicit authorization.
  • Backups: never overwrite original data without a recoverable copy.
  • Data governance: respect privacy, access controls, and data classification.
  • Production: never connect scripts to real sources without review, approval, and rollback planning.

Objetivo del Topic 1

El objetivo es tomar un archivo de Excel con encabezados inconsistentes como Employee ID, Emp Id, ID Empleado o Email Address, y convertirlos en nombres estándar que sean fáciles de usar en Python, Power BI, SQL o validaciones posteriores.

01 · Crear Excel crudo
02 · Normalizar columnas
03 · Verificar resultado
Idea central: antes de limpiar valores, cruzar tablas o crear dashboards, la estructura de columnas debe ser consistente.

Topic 1 Objective

The goal is to take an Excel file with inconsistent headers such as Employee ID, Emp Id, ID Empleado, or Email Address, and convert them into standard names that are easier to use in Python, Power BI, SQL, or later validations.

01 · Create raw Excel
02 · Normalize columns
03 · Verify result
Core idea: before cleaning values, matching tables, or creating dashboards, the column structure must be consistent.

Ruta de trabajo

Todo se ejecuta dentro de una carpeta controlada:

Working folder

Everything runs inside a controlled folder:

BasePath = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 1"

Qué vamos a aprender

  • Crear un Excel sintético con columnas inconsistentes.
  • Leer Excel con pandas.
  • Limpiar espacios, mayúsculas, guiones y símbolos.
  • Aplicar un diccionario de nombres estándar.
  • Exportar un Excel limpio y un reporte de cambios.

What you will learn

  • Create a synthetic Excel file with inconsistent columns.
  • Read Excel with pandas.
  • Clean spaces, uppercase/lowercase, hyphens, and symbols.
  • Apply a standard column-name dictionary.
  • Export a clean Excel file and a change report.
01

Script 1 — Crear data sintética en Excel

Este script crea un archivo de Excel con columnas desordenadas. Es una copia de práctica, no data real.

Script 1 — Create synthetic Excel data

This script creates an Excel file with messy columns. It is practice data, not real data.

# ======================================================
# Python Topic 1 - Script 1
# Create synthetic Excel data with inconsistent columns
# ======================================================

from pathlib import Path
import pandas as pd

base_path = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 1"
data_path = base_path / "Data"
data_path.mkdir(parents=True, exist_ok=True)

raw_file = data_path / "employees_raw.xlsx"

df = pd.DataFrame({
    " Employee ID ": ["10001", "10002", "10003", "10004"],
    "First Name": ["John", "Maria", "Carlos", "Ana"],
    "LAST-NAME": ["Smith", "Garcia", "Rivera", "Lopez"],
    "Dept Name": ["Finance", "HR", "IT", "Operations"],
    "Email Address": [
        "john.smith@example.com",
        "maria.garcia@example.com",
        "carlos.rivera@example.com",
        "ana.lopez@example.com"
    ]
})

df.to_excel(raw_file, index=False)

print("Synthetic Excel file created:")
print(raw_file)
print(df.head())
02

Script 2 — Normalizar columnas inconsistentes

Este script lee el Excel crudo, limpia los encabezados y aplica nombres estándar usando un diccionario.

Script 2 — Normalize inconsistent columns

This script reads the raw Excel file, cleans the headers, and applies standard names using a dictionary.

# ======================================================
# Python Topic 1 - Script 2
# Normalize inconsistent column names
# ======================================================

from pathlib import Path
import pandas as pd

base_path = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 1"
data_path = base_path / "Data"

raw_file = data_path / "employees_raw.xlsx"
clean_file = data_path / "employees_clean_columns.xlsx"
mapping_report_file = data_path / "column_mapping_report.xlsx"

df = pd.read_excel(raw_file)

original_columns = list(df.columns)

# Basic normalization: trim, lowercase, replace spaces/hyphens with underscores
df.columns = (
    df.columns
    .str.strip()
    .str.lower()
    .str.replace(" ", "_", regex=False)
    .str.replace("-", "_", regex=False)
)

# Business-friendly standard names
standard_map = {
    "employee_id": "Employee_ID",
    "first_name": "FirstName",
    "last_name": "LastName",
    "dept_name": "Department",
    "email_address": "Email"
}

df = df.rename(columns=standard_map)

mapping_report = pd.DataFrame({
    "Original_Column": original_columns,
    "Normalized_Column": list(df.columns)
})

df.to_excel(clean_file, index=False)
mapping_report.to_excel(mapping_report_file, index=False)

print("Clean Excel file created:")
print(clean_file)

print("Column mapping report created:")
print(mapping_report_file)
Nota: este script no sobrescribe el Excel original. Crea un archivo limpio y un reporte de mapeo para auditoría.
Note: this script does not overwrite the original Excel file. It creates a clean file and a mapping report for audit.
03

Script 3 — Verificar resultado

Este script abre el archivo limpio y muestra las columnas finales para confirmar que quedaron estándar.

Script 3 — Verify result

This script opens the clean file and displays the final columns to confirm they are standardized.

# ======================================================
# Python Topic 1 - Script 3
# Verify standardized columns
# ======================================================

from pathlib import Path
import pandas as pd

base_path = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 1"
data_path = base_path / "Data"

clean_file = data_path / "employees_clean_columns.xlsx"
mapping_report_file = data_path / "column_mapping_report.xlsx"

clean_df = pd.read_excel(clean_file)
mapping_df = pd.read_excel(mapping_report_file)

print("Final columns:")
print(list(clean_df.columns))

print("\nColumn mapping:")
print(mapping_df)

print("\nPreview:")
print(clean_df.head())

Explicación simple del script

  • pd.read_excel() carga el archivo original.
  • str.strip() elimina espacios al inicio y al final del nombre de columna.
  • str.lower() convierte los encabezados a minúscula para estandarizar.
  • str.replace() reemplaza espacios y guiones por guiones bajos.
  • rename(columns=...) aplica nombres finales amigables para el negocio.
  • to_excel() exporta el archivo limpio y el reporte.

Simple script explanation

  • pd.read_excel() loads the original file.
  • str.strip() removes leading and trailing spaces from column names.
  • str.lower() converts headers to lowercase for consistency.
  • str.replace() replaces spaces and hyphens with underscores.
  • rename(columns=...) applies final business-friendly names.
  • to_excel() exports the clean file and the report.

Ejemplo esperado

AntesDespués
Employee ID Employee_ID
First NameFirstName
LAST-NAMELastName
Dept NameDepartment
Email AddressEmail

Expected example

BeforeAfter
Employee ID Employee_ID
First NameFirstName
LAST-NAMELastName
Dept NameDepartment
Email AddressEmail

Conclusión

Este topic enseña una base esencial de Python para datos: controlar la estructura antes de transformar contenido. Si las columnas son inconsistentes, cualquier validación, cruce o dashboard puede fallar o requerir trabajo manual adicional.

Lección clave: un buen flujo de limpieza empieza por columnas claras, estables y auditables.

Conclusion

This topic teaches an essential Python data foundation: control the structure before transforming the content. If columns are inconsistent, any validation, match, or dashboard can fail or require additional manual work.

Key lesson: a good cleaning workflow starts with clear, stable, and auditable columns.