Executive SnapshotResumen Ejecutivo
Official Data SourceFuente Oficial de Datos
The case uses the public dataset Police Department Incident Reports: 2018 to Present, published through DataSF by the San Francisco Police Department, and loaded into the governed Databricks table workspace.default.police_incidents.
El caso utiliza el dataset público Police Department Incident Reports: 2018 to Present, publicado mediante DataSF por el San Francisco Police Department, y cargado en la tabla gobernada de Databricks workspace.default.police_incidents.
The findings represent the specific public extract available in the workspace, not the complete live operational police database.
Los hallazgos representan el extracto público específico disponible en el workspace, no la base operacional policial completa y en vivo.
Databricks + Apache Spark + Governed Pipeline
Databricks provides the governed collaborative environment; Apache Spark provides distributed parallel processing; PySpark expresses the investigation as reusable code. In production, the pipeline would include lineage, role-based access, least privilege, encryption, monitoring, privacy controls and separate development, test and production environments.
Databricks proporciona el ambiente colaborativo gobernado; Apache Spark proporciona procesamiento paralelo distribuido; PySpark expresa la investigación como código reutilizable. En producción, el pipeline incluiría linaje, acceso basado en roles, mínimo privilegio, cifrado, monitoreo, controles de privacidad y ambientes separados de desarrollo, prueba y producción.
Investigation TreeÁrbol de Investigación
NavigationNavegación
Load the Governed Analytical TableCargar la Tabla Analítica Gobernada
1. Business QuestionPregunta de Negocio
Can the investigation begin from an identified, governed and reproducible table?¿Puede comenzar la investigación desde una tabla identificada, gobernada y reproducible?
2. Why This MattersPor Qué Importa
A professional analysis must establish exactly which object is being analyzed before any metric is calculated.Un análisis profesional debe establecer exactamente qué objeto se analiza antes de calcular cualquier métrica.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
from pyspark.sql.functions import *
df = spark.table("workspace.default.police_incidents")
record_count = df.count()
column_count = len(df.columns)
print(f"Records: {record_count:,}")
print(f"Columns: {column_count}")
df.printSchema()
display(df.limit(10))
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
The table is large enough to demonstrate distributed processing while remaining practical for an instructional investigation.La tabla es suficientemente grande para demostrar procesamiento distribuido y a la vez práctica para una investigación educativa.
7. Executive InterpretationInterpretación Ejecutiva
The analytical object is identifiable, repeatable and ready for controlled investigation.El objeto analítico es identificable, repetible y está listo para una investigación controlada.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Validate temporal scope and completeness.Validar el alcance temporal y la integridad.
Validate Time Coverage and Partial-Year RiskValidar Cobertura Temporal y Riesgo de Año Parcial
1. Business QuestionPregunta de Negocio
What time period does the published extract actually cover?¿Qué período cubre realmente el extracto publicado?
2. Why This MattersPor Qué Importa
Comparing incomplete years with complete years can create false operational conclusions.Comparar años incompletos con años completos puede producir conclusiones operacionales falsas.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
df_dates = (
df.withColumn("Incident_Date_Parsed", to_date("Incident_Date", "yyyy/MM/dd"))
)
date_scope = df_dates.agg(
min("Incident_Date_Parsed").alias("Minimum_Date"),
max("Incident_Date_Parsed").alias("Maximum_Date")
)
yearly_counts = (
df.groupBy("Incident_Year")
.agg(count("Incident_ID").alias("Total_Incidents"))
.orderBy("Incident_Year")
)
display(date_scope)
display(yearly_counts)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
2018–2023 are broadly comparable full-year periods; 2024 requires explicit exclusion or normalization.2018–2023 son períodos anuales completos ampliamente comparables; 2024 requiere exclusión explícita o normalización.
7. Executive InterpretationInterpretación Ejecutiva
The investigation must separate complete and incomplete periods before any trend ranking.La investigación debe separar períodos completos e incompletos antes de cualquier ranking de tendencias.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Establish the annual incident baseline.Establecer la línea base anual de incidentes.
Establish the Annual Incident BaselineEstablecer la Línea Base Anual de Incidentes
1. Business QuestionPregunta de Negocio
How did total incident volume evolve by year?¿Cómo evolucionó el volumen total de incidentes por año?
2. Why This MattersPor Qué Importa
The annual baseline reveals structural shifts that require category-level decomposition.La línea base anual revela cambios estructurales que requieren descomposición por categoría.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
annual_incidents = (
df.groupBy("Incident_Year")
.agg(count("Incident_ID").alias("Total_Incidents"))
.orderBy("Incident_Year")
)
display(annual_incidents)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
The largest complete-year disruption occurred in 2020, followed by recovery without a full return to the 2018 level.La mayor ruptura entre años completos ocurrió en 2020, seguida de recuperación sin retorno completo al nivel de 2018.
7. Executive InterpretationInterpretación Ejecutiva
A global decline does not reveal which operational categories changed or in what direction.Una disminución global no revela qué categorías operacionales cambiaron ni en qué dirección.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Measure category volume and percentage share.Medir volumen y participación porcentual por categoría.
Measure Incident Category DistributionMedir la Distribución de Categorías de Incidentes
1. Business QuestionPregunta de Negocio
Which incident categories dominate the published operational workload?¿Qué categorías dominan la carga operacional publicada?
2. Why This MattersPor Qué Importa
Counts without percentage share do not show relative operational importance.Los conteos sin participación porcentual no muestran la importancia operacional relativa.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
total_incidents = df.count()
category_share = (
df.groupBy("Incident_Category")
.agg(count("Incident_ID").alias("Incidents"))
.withColumn(
"Share_Percentage",
round((col("Incidents") / lit(total_incidents)) * 100, 2)
)
.orderBy(col("Incidents").desc())
)
display(category_share)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
One category alone accounts for almost three of every ten published incidents.Una sola categoría representa casi tres de cada diez incidentes publicados.
7. Executive InterpretationInterpretación Ejecutiva
Larceny Theft is the natural first branch, but category concentration alone does not explain the 2020 change.Larceny Theft es la primera rama natural, pero la concentración por categoría no explica por sí sola el cambio de 2020.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Build the Larceny Theft annual trend.Construir la tendencia anual de Larceny Theft.
Normalize the Larceny Theft TrendNormalizar la Tendencia de Larceny Theft
1. Business QuestionPregunta de Negocio
Did Larceny Theft fall only in count, or also as a share of all incidents?¿Larceny Theft cayó solo en conteo o también como participación de todos los incidentes?
2. Why This MattersPor Qué Importa
A category can decline in count simply because the entire dataset declined. Normalization tests whether its operational weight also changed.Una categoría puede disminuir en conteo simplemente porque disminuyó todo el dataset. La normalización prueba si también cambió su peso operacional.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
annual_total = (
df.groupBy("Incident_Year")
.agg(count("Incident_ID").alias("Total_Incidents"))
)
larceny_year = (
df.filter(col("Incident_Category") == "Larceny Theft")
.groupBy("Incident_Year")
.agg(count("Incident_ID").alias("Larceny_Incidents"))
)
larceny_trend = (
larceny_year.join(annual_total, "Incident_Year")
.withColumn(
"Larceny_Share",
round((col("Larceny_Incidents") / col("Total_Incidents")) * 100, 2)
)
.orderBy("Incident_Year")
)
display(larceny_trend)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
The decline was real in both absolute and relative terms.La disminución fue real tanto en términos absolutos como relativos.
7. Executive InterpretationInterpretación Ejecutiva
Larceny Theft explains much of the global decline, but it cannot support the claim that every category declined.Larceny Theft explica gran parte de la caída global, pero no respalda la afirmación de que todas las categorías disminuyeron.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Create a category pivot and rank absolute and percentage change.Crear un pivot por categoría y clasificar cambio absoluto y porcentual.
Compare Every Category: 2019 vs 2020Comparar Todas las Categorías: 2019 vs 2020
1. Business QuestionPregunta de Negocio
Did all incident categories decline during 2020?¿Disminuyeron todas las categorías de incidentes durante 2020?
2. Why This MattersPor Qué Importa
A global trend can hide opposing movements among its components.Una tendencia global puede ocultar movimientos opuestos entre sus componentes.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
category_comparison = (
df.filter(col("Incident_Year").isin(2019, 2020))
.groupBy("Incident_Category")
.pivot("Incident_Year", [2019, 2020])
.agg(count("Incident_ID"))
.fillna(0)
.withColumn("Difference", col("2020") - col("2019"))
.withColumn("Absolute_Change", abs(col("Difference")))
.withColumn(
"Percent_Change",
when(
col("2019") > 0,
round((col("Difference") / col("2019")) * 100, 2)
)
)
.orderBy(col("Absolute_Change").desc())
)
display(category_comparison)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
The 2020 disruption changed the incident mix rather than simply reducing all categories uniformly.La ruptura de 2020 cambió la composición de incidentes en lugar de reducir uniformemente todas las categorías.
7. Executive InterpretationInterpretación Ejecutiva
The hypothesis that every category declined is rejected. Burglary becomes the strongest explanatory branch because it combines high percentage growth with substantial absolute impact.Se rechaza la hipótesis de que todas las categorías disminuyeron. Burglary se convierte en la rama explicativa más fuerte porque combina alto crecimiento porcentual con impacto absoluto sustancial.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Measure which districts contributed most to the increase.Medir qué distritos contribuyeron más al aumento.
Decompose Burglary Growth by Police DistrictDescomponer el Crecimiento de Burglary por Distrito Policial
1. Business QuestionPregunta de Negocio
Which police districts contributed most to the burglary increase?¿Qué distritos policiales contribuyeron más al aumento de burglary?
2. Why This MattersPor Qué Importa
Operational resources are assigned geographically; citywide averages are not directly actionable.Los recursos operacionales se asignan geográficamente; los promedios de toda la ciudad no son directamente accionables.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
burglary_district = (
df.filter(
(col("Incident_Category") == "Burglary") &
(col("Incident_Year").isin(2019, 2020))
)
.groupBy("Police_District")
.pivot("Incident_Year", [2019, 2020])
.agg(count("Incident_ID"))
.fillna(0)
.withColumn("Difference", col("2020") - col("2019"))
.withColumn(
"Percent_Change",
when(col("2019") > 0, round((col("2020")-col("2019"))/col("2019")*100,2))
)
.orderBy(col("Difference").desc())
)
display(burglary_district)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
Northern had the greatest absolute impact, while Park had the greatest relative increase.Northern tuvo el mayor impacto absoluto, mientras Park tuvo el mayor aumento relativo.
7. Executive InterpretationInterpretación Ejecutiva
Absolute and relative rankings answer different management questions. Both must be preserved.Los rankings absoluto y relativo responden preguntas gerenciales diferentes. Ambos deben conservarse.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Measure neighborhood concentration within Northern District.Medir la concentración por barrios dentro de Northern District.
Measure Neighborhood Concentration in Northern DistrictMedir la Concentración por Barrios en Northern District
1. Business QuestionPregunta de Negocio
Was Northern District burglary growth broadly distributed or concentrated in a few neighborhoods?¿El crecimiento de burglary en Northern District estuvo ampliamente distribuido o concentrado en pocos barrios?
2. Why This MattersPor Qué Importa
Concentration reveals whether broad deployment or targeted intervention is more appropriate.La concentración revela si es más apropiado un despliegue amplio o una intervención focalizada.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
northern_2020 = (
df.filter(
(col("Incident_Category") == "Burglary") &
(col("Incident_Year") == 2020) &
(col("Police_District") == "Northern")
)
)
total_northern = northern_2020.count()
neighborhood_share = (
northern_2020.groupBy("Analysis_Neighborhood")
.agg(count("Incident_ID").alias("Burglary_Incidents"))
.withColumn(
"Share_Percentage",
round((col("Burglary_Incidents") / lit(total_northern)) * 100, 2)
)
.orderBy(col("Burglary_Incidents").desc())
)
display(neighborhood_share)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
Nearly two thirds of Northern District burglary incidents were concentrated in three neighborhoods.Casi dos tercios de los incidentes de burglary de Northern District se concentraron en tres barrios.
7. Executive InterpretationInterpretación Ejecutiva
The evidence favors targeted geographic analysis over district-wide generalization.La evidencia favorece un análisis geográfico focalizado sobre una generalización de todo el distrito.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Test whether day of week provides a strong operational signal.Probar si el día de la semana proporciona una señal operacional fuerte.
Test the Day-of-Week HypothesisProbar la Hipótesis por Día de Semana
1. Business QuestionPregunta de Negocio
Is burglary strongly concentrated on weekends?¿Burglary está fuertemente concentrado en fines de semana?
2. Why This MattersPor Qué Importa
A strong day pattern could influence shift planning and preventive coverage.Un patrón fuerte por día podría influir en la planificación de turnos y cobertura preventiva.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
burglary_day = (
df.filter(col("Incident_Category") == "Burglary")
.groupBy("Incident_Day_of_Week")
.agg(count("Incident_ID").alias("Burglary_Incidents"))
)
total_burglary = burglary_day.agg(
sum("Burglary_Incidents").alias("Total")
).first()["Total"]
burglary_day_share = (
burglary_day.withColumn(
"Share_Percentage",
round((col("Burglary_Incidents") / lit(total_burglary)) * 100, 2)
)
.orderBy(col("Burglary_Incidents").desc())
)
display(burglary_day_share)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
The distribution is relatively even and does not show meaningful weekend concentration.La distribución es relativamente uniforme y no muestra concentración significativa en fines de semana.
7. Executive InterpretationInterpretación Ejecutiva
Day of week is a weak discriminator for resource allocation by itself.El día de la semana es un discriminador débil para asignación de recursos por sí solo.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Extract and analyze incident hour.Extraer y analizar la hora del incidente.
Analyze Hour-of-Day BehaviorAnalizar el Comportamiento por Hora del Día
1. Business QuestionPregunta de Negocio
Does hour of day reveal stronger burglary behavior than day of week?¿La hora del día revela un comportamiento de burglary más fuerte que el día de la semana?
2. Why This MattersPor Qué Importa
Hourly profiles can support more precise operational windows than daily averages.Los perfiles horarios pueden apoyar ventanas operacionales más precisas que los promedios diarios.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
df_hour = (
df.withColumn(
"Incident_Timestamp",
to_timestamp("Incident_Datetime", "yyyy/MM/dd hh:mm:ss a")
)
.withColumn("Incident_Hour", hour("Incident_Timestamp"))
)
burglary_hour = (
df_hour.filter(col("Incident_Category") == "Burglary")
.groupBy("Incident_Hour")
.agg(count("Incident_ID").alias("Burglary_Incidents"))
.orderBy("Incident_Hour")
)
display(burglary_hour)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
There appears to be more than one operational pattern rather than a single universal peak.Parece existir más de un patrón operacional en lugar de un único pico universal.
7. Executive InterpretationInterpretación Ejecutiva
A citywide hourly profile can still hide different neighborhood behaviors.Un perfil horario de toda la ciudad todavía puede ocultar comportamientos diferentes por barrio.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Compare neighborhood-specific hourly profiles.Comparar perfiles horarios específicos por barrio.
Build the Neighborhood × Hour Behavioral MatrixConstruir la Matriz de Comportamiento Barrio × Hora
1. Business QuestionPregunta de Negocio
Do different neighborhoods exhibit distinct burglary hour profiles?¿Diferentes barrios presentan perfiles horarios distintos de burglary?
2. Why This MattersPor Qué Importa
Distinct profiles would support differentiated operating strategies instead of one citywide schedule.Perfiles distintos apoyarían estrategias operacionales diferenciadas en lugar de un solo horario para toda la ciudad.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
hour_neighborhood = (
df_hour.filter(col("Incident_Category") == "Burglary")
.groupBy("Analysis_Neighborhood", "Incident_Hour")
.agg(count("Incident_ID").alias("Burglary_Incidents"))
.orderBy("Analysis_Neighborhood", "Incident_Hour")
)
display(hour_neighborhood)
financial_profile = (
hour_neighborhood.filter(
col("Analysis_Neighborhood") == "Financial District/South Beach"
)
)
display(financial_profile)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
The visible profile supports the possibility of neighborhood-specific behavior, but external land-use validation is still required.El perfil visible respalda la posibilidad de comportamientos específicos por barrio, pero todavía se requiere validación externa del uso del suelo.
7. Executive InterpretationInterpretación Ejecutiva
This branch is promising but not yet fully closed. It should remain in the future investigation roadmap.Esta rama es prometedora pero aún no está completamente cerrada. Debe permanecer en la hoja de ruta de futuras investigaciones.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Validate missing neighborhood values before deeper segmentation.Validar valores faltantes de barrio antes de una segmentación más profunda.
Validate Missing Neighborhood ValuesValidar Valores Faltantes de Barrio
1. Business QuestionPregunta de Negocio
Could missing neighborhood values materially distort the burglary analysis?¿Podrían los valores faltantes de barrio distorsionar materialmente el análisis de burglary?
2. Why This MattersPor Qué Importa
Visible NULL rows can appear important without measuring their actual volume.Las filas NULL visibles pueden parecer importantes sin medir su volumen real.
3. Working HypothesisHipótesis de Trabajo
4. Spark Investigation
missing_burglary_neighborhood = (
df.filter(
(col("Incident_Category") == "Burglary") &
(col("Analysis_Neighborhood").isNull())
)
.agg(count("Incident_ID").alias("Missing_Neighborhood_Records"))
)
display(missing_burglary_neighborhood)
5. Actual EvidenceEvidencia Real
6. Pattern ObservedPatrón Observado
The apparent issue was visually noticeable but operationally negligible.El problema aparente era visualmente notable pero operacionalmente insignificante.
7. Executive InterpretationInterpretación Ejecutiva
The data-quality hypothesis is rejected. The investigation can continue without material bias from this field.Se rechaza la hipótesis de calidad de datos. La investigación puede continuar sin sesgo material proveniente de este campo.
8. Decision ImpactImpacto en la Decisión
9. Next InvestigationPróxima Investigación
Move toward operational priority modeling, hotspot persistence and governed forecasting.Avanzar hacia modelado de prioridad operacional, persistencia de hotspots y pronóstico gobernado.
Executive Findings and Closed Information CycleHallazgos Ejecutivos y Ciclo de Información Cerrado
- Larceny Theft dominates the incident mix at 29.04%.
- The 2020 decline was not uniform across categories.
- Burglary increased 53.71% and Motor Vehicle Theft increased 40.94%.
- Northern produced the largest absolute district burglary increase.
- Three Northern neighborhoods represented 63.97% of 2020 burglary incidents.
- Day of week was a weak discriminator; hour and neighborhood combinations were more promising.
Cycle closure: The case defines its scope, gathers sufficient evidence, rejects unsupported hypotheses, closes one coherent information cycle and preserves future branches without pretending that every possible question has been answered.
Cierre del ciclo: El caso define su alcance, reúne evidencia suficiente, rechaza hipótesis no respaldadas, cierra un ciclo coherente de información y conserva ramas futuras sin pretender que todas las preguntas posibles han sido respondidas.
Common MistakesErrores Comunes
- Comparing partial 2024 with complete years.
- Using counts without percentages.
- Ranking only by percentage change.
- Drawing causal conclusions from descriptive public data.
- Ignoring the level of aggregation required by the business question.
- Treating a visible NULL value as important before measuring its frequency.
Future Investigation RoadmapHoja de Ruta de Investigaciones Futuras
- Mission vs Financial District hourly comparison.
- Residential, commercial and mixed-use behavioral segmentation.
- Motor Vehicle Theft and recovery analysis.
- Resolution effectiveness by category and district.
- Hotspot persistence and geospatial clustering.
- Operational Priority Index.
- Patrol allocation scenarios.
- Governed forecasting and anomaly detection.
Final Methodological StatementDeclaración Metodológica Final
Databricks is not used merely to run code. It is used as a governed analytical environment where public data moves through a secure, automated and scalable pipeline, while Apache Spark supplies the parallel processing capacity required to transform large operational datasets into reproducible evidence and executive decisions.
Databricks no se utiliza solamente para ejecutar código. Se utiliza como un ambiente analítico gobernado donde los datos públicos se mueven mediante un pipeline seguro, automatizado y escalable, mientras Apache Spark aporta la capacidad de procesamiento paralelo necesaria para transformar grandes datasets operacionales en evidencia reproducible y decisiones ejecutivas.
Cybersecurity and Production NoticeAviso de Ciberseguridad y Producción
This material uses public, non-production data for education and analytical demonstration. Production deployment requires formal legal, privacy, governance, security, performance and operational approval.
Este material utiliza datos públicos y no productivos para educación y demostración analítica. El despliegue en producción requiere aprobación formal legal, de privacidad, gobernanza, seguridad, rendimiento y operaciones.