Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

cleandata.py 28 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
  1. import pandas as pd
  2. from datetime import datetime
  3. from pjud import data
  4. import os
  5. from tqdm.auto import tqdm
  6. import numpy as np
  7. import click
  8. def convierte_fecha(fecha):
  9. try:
  10. day,month,year = map(int,fecha.split(sep = "-"))
  11. except:
  12. #print(f"no pude ejecutar {fecha}")
  13. return pd.NaT
  14. return datetime(year,month,day)
  15. def obtiene_año(rit):
  16. try:
  17. rol,year = map(int,rit.split(sep = "-"))
  18. except:
  19. #print(f"no pude ejecutar {fecha}")
  20. return pd.NaT
  21. return (year)
  22. def elimina_tilde(str_variable):
  23. replacements = {'Á': 'A',
  24. 'É': 'E',
  25. 'Í': 'I',
  26. 'Ó': 'O',
  27. 'Ú': 'U',
  28. 'Ü': 'U',
  29. }
  30. for a, b in replacements.items():
  31. str_variable = str_variable.astype(str).str.replace(a, b)
  32. return str_variable
  33. def elimina_espacios(col):
  34. if col.dtypes == object:
  35. return (col.astype(str).str.rstrip())
  36. return col
  37. def limpia_rit(str_rit):
  38. return str_rit.replace('--','-')
  39. def limpieza_caracteres(str_col):
  40. replacements = {'-': '',
  41. '\xa0': '',
  42. '\n': ''
  43. }
  44. for a, b in replacements.items():
  45. str_col = str_col.astype(str).str.replace(a, b)
  46. return str_col
  47. def transforma_numero(str_numero):
  48. replacements = {"ún": "1",
  49. "un": "1",
  50. "dós": "2",
  51. "dos": "2",
  52. "tres": "3",
  53. "cuatro": "4",
  54. "cinco": "5",
  55. "seis": "6",
  56. "seís": "6",
  57. "séis": "6",
  58. "siete": "7",
  59. "ocho": "8",
  60. "nueve": "9",
  61. "diez": "10",
  62. "once": "11",
  63. "doce": "12",
  64. "trece": "13",
  65. "dieci": "1",
  66. "veinti": "2",
  67. "veinte": "20"
  68. }
  69. for a, b in replacements.items():
  70. str_numero = str_numero.replace(a, b)
  71. return str_numero
  72. def separa_regiones(str_region):
  73. reemplazar_region = {"DECIMA REGION": "REGION",
  74. "UNDECIMA REGION": "REGION",
  75. "DUODECIMA REGION": "REGION",
  76. "DECIMOCUARTA REGION": "REGION",
  77. "DECIMOQUINTA REGION": "REGION",
  78. "PRIMERA REGION": "REGION",
  79. "SEGUNDA REGION": "REGION",
  80. "TERCERA REGION": "REGION",
  81. "CUARTA REGION": "REGION",
  82. "QUINTA REGION": "REGION",
  83. "SEXTA REGION": "REGION",
  84. "SEPTIMA REGION": "REGION",
  85. "OCTAVA REGION": "REGION",
  86. "NOVENA REGION": "REGION",
  87. "BIOBIO": "REGION DEL BIO BIO",
  88. "AYSEN": "REGION DE AISEN",
  89. "MAGALLANES Y DE LA ANTARTICA CHILENA": "REGION DE MAGALLANES Y ANTARTICA CHILENA"
  90. }
  91. for old, new in reemplazar_region.items():
  92. str_region = str_region.replace(old, new)
  93. return str_region
  94. def transforma_asiento(str_asiento):
  95. if str_asiento.find("JUZGADO DE GARANTIA") != -1 or str_asiento.find("TRIBUNAL DE JUICIO ORAL EN LO PENAL") != -1:
  96. str_asiento = "SANTIAGO"
  97. return str_asiento
  98. def cambio_nombre_juzgados(str_tribunal):
  99. reemplazar_texto = {"1º JUZGADO DE LETRAS": "JUZGADO DE LETRAS",
  100. "6º TRIBUNAL DE JUICIO ORAL EN LO PENAL DE SAN MIGUEL": "SEXTO TRIBUNAL DE JUICIO ORAL EN LO PENAL SANTIAGO",
  101. "10º JUZGADO DE GARANTIA": "DECIMO JUZGADO DE GARANTIA",
  102. "11º JUZGADO DE GARANTIA": "UNDECIMO JUZGADO DE GARANTIA",
  103. "12º JUZGADO DE GARANTIA": "DUODECIMO JUZGADO DE GARANTIA",
  104. "13º JUZGADO DE GARANTIA": "DECIMOTERCER JUZGADO DE GARANTIA",
  105. "14º JUZGADO DE GARANTIA": "DECIMOCUARTO JUZGADO DE GARANTIA",
  106. "15º JUZGADO DE GARANTIA": "DECIMOQUINTO JUZGADO DE GARANTIA",
  107. "TRIBUNAL ORAL EN LO PENAL DE": "TRIBUNAL DE JUICIO ORAL EN LO PENAL",
  108. "1º": "PRIMER",
  109. "2º": "SEGUNDO",
  110. "3º": "TERCER",
  111. "4º": "CUARTO",
  112. "5º": "QUINTO",
  113. "6º": "SEXTO",
  114. "7º": "SEPTIMO",
  115. "8º": "OCTAVO",
  116. "9º": "NOVENO",
  117. "TRIBUNAL DE JUICIO ORAL EN LO PENAL DE DE ": "TRIBUNAL DE JUICIO ORAL EN LO PENAL ",
  118. "TRIBUNAL DE JUICIO ORAL EN LO PENAL DE": "TRIBUNAL DE JUICIO ORAL EN LO PENAL",
  119. "JUZGADO DE GARANTIA DE DE ": "JUZGADO DE GARANTIA ",
  120. "JUZGADO DE GARANTIA DE": "JUZGADO DE GARANTIA",
  121. "JUZGADO DE LETRAS Y GARANTIA DE": "JUZGADO DE LETRAS Y GARANTIA",
  122. "JUZGADO DE LETRAS DE": "JUZGADO DE LETRAS Y GARANTIA",
  123. "LA CALERA": "CALERA",
  124. "PUERTO NATALES": "NATALES",
  125. "PUERTO AYSEN": "AISEN",
  126. "PUERTO CISNES": "CISNES",
  127. "SAN VICENTE DE TAGUA-TAGUA": "SAN VICENTE",
  128. "ACHAO": "QUINCHAO",
  129. "COYHAIQUE": "COIHAIQUE"
  130. }
  131. for old, new in reemplazar_texto.items():
  132. str_tribunal = str_tribunal.replace(old, new)
  133. return str_tribunal
  134. def cambio_termino_causa(str_termino):
  135. if pd.notnull(str_termino):
  136. str_termino = str_termino.replace(".","")
  137. return str_termino
  138. def load_concatenate_by_filename(needle: str, src_path = "data/raw/pjud"):
  139. archivos = os.listdir(src_path)
  140. tqdm.pandas()
  141. dataframes = []
  142. for archivo in archivos:
  143. if archivo.find(needle) != -1:
  144. df = pd.read_csv(f"{src_path}/{archivo}", sep=";", encoding='cp850', dtype='unicode', low_memory=True)
  145. dataframes.append(df)
  146. return pd.concat(dataframes)
  147. def carga_limpieza_ingresos_materia():
  148. df_ingresos_materia = load_concatenate_by_filename('Ingresos por Materia Penal')
  149. df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'] = df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'].fillna(
  150. df_ingresos_materia['TOTAL INGRESOS POR MATERIAS(*)'])
  151. df_ingresos_materia.drop(['N°', 'TOTAL INGRESOS POR MATERIAS(*)'], axis='columns', inplace=True)
  152. df_ingresos_materia.drop([
  153. '(*)Se agregó columna total de ingresos, dado que en algunas causas, la materia se repite (error de tramitación)'],
  154. axis='columns', inplace=True)
  155. # TRANSFORMAMOS DE FLOAT A INTEGER
  156. df_ingresos_materia['COD. CORTE'] = df_ingresos_materia['COD. CORTE'].fillna(0).astype(np.int16)
  157. df_ingresos_materia['COD. TRIBUNAL'] = df_ingresos_materia['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  158. df_ingresos_materia['COD. MATERIA'] = df_ingresos_materia['COD. MATERIA'].fillna(0).astype(np.int16)
  159. df_ingresos_materia['AÑO INGRESO'] = df_ingresos_materia['AÑO INGRESO'].fillna(0).astype(np.int16)
  160. df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'] = df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'].fillna(0).astype(np.int8)
  161. # Transformamos fechas
  162. click.echo('Transformando fechas')
  163. df_ingresos_materia['FECHA INGRESO'] = df_ingresos_materia['FECHA INGRESO'].progress_apply(convierte_fecha)
  164. # Elimino espacios en las columnas tipo objetos
  165. click.echo('Eliminando espacios en objetos')
  166. df_ingresos_materia = df_ingresos_materia.progress_apply(elimina_espacios, axis=0)
  167. # Elimino tildes
  168. click.echo('Eliminando tildes')
  169. cols = df_ingresos_materia.select_dtypes(include=["object"]).columns
  170. df_ingresos_materia[cols] = df_ingresos_materia[cols].progress_apply(elimina_tilde)
  171. # Categorizacion
  172. df_ingresos_materia['CORTE'] = df_ingresos_materia['CORTE'].astype('category')
  173. tipo_causa = df_ingresos_materia[df_ingresos_materia['TIPO CAUSA'] != 'Ordinaria']
  174. df_ingresos_materia.drop(tipo_causa.index, axis=0, inplace=True)
  175. data.save_feather(df_ingresos_materia, 'clean_IngresosMateria')
  176. click.echo("Generado archivo Feather 'clean_IngresosMateria.feather'. Proceso Terminado")
  177. def carga_limpieza_terminos_materia():
  178. df_termino_materia = load_concatenate_by_filename('Términos por Materia Penal')
  179. df_metge = df_termino_materia[df_termino_materia['SISTEMA']=='METGE']
  180. df_termino_materia.drop(df_metge.index, axis=0, inplace=True)
  181. # Estandarización de nombres de variables
  182. df_termino_materia.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  183. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  184. 'CÓD. MATERIA':'COD. MATERIA',
  185. 'MOTIVO DE TÉRMINO':'MOTIVO TERMINO',
  186. 'DURACIÓN CAUSA':'DURACION CAUSA',
  187. 'FECHA TÉRMINO':'FECHA TERMINO',
  188. 'MES TÉRMINO':'MES TERMINO',
  189. 'AÑO TÉRMINO':'AÑO TERMINO',
  190. 'TOTAL TÉRMINOS':'TOTAL TERMINOS'
  191. },inplace = True)
  192. df_termino_materia.drop(['N°','SISTEMA'], axis = 'columns', inplace = True)
  193. # TRANSFORMAMOS DE FLOAT A INTEGER
  194. df_termino_materia['COD. CORTE'] = df_termino_materia['COD. CORTE'].fillna(0).astype(np.int16)
  195. df_termino_materia['COD. TRIBUNAL'] = df_termino_materia['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  196. df_termino_materia['COD. MATERIA'] = df_termino_materia['COD. MATERIA'].fillna(0).astype(np.int16)
  197. df_termino_materia['DURACION CAUSA'] = df_termino_materia['DURACION CAUSA'].fillna(0).astype(np.int16)
  198. df_termino_materia['AÑO TERMINO'] = df_termino_materia['AÑO TERMINO'].fillna(0).astype(np.int16)
  199. df_termino_materia['TOTAL TERMINOS'] = df_termino_materia['TOTAL TERMINOS'].fillna(0).astype(np.int8)
  200. # Transformamos formato fecha
  201. click.echo('Convirtiendo fechas')
  202. df_termino_materia['FECHA INGRESO'] = df_termino_materia['FECHA INGRESO'].progress_apply(convierte_fecha)
  203. df_termino_materia['FECHA TERMINO'] = df_termino_materia['FECHA TERMINO'].progress_apply(convierte_fecha)
  204. # Elimino espacios en las columnas tipo objetos
  205. click.echo('Eliminando espacios')
  206. df_termino_materia = df_termino_materia.progress_apply(elimina_espacios, axis=0)
  207. # Elimino tildes de object
  208. click.echo('Eliminando tilde')
  209. cols = df_termino_materia.select_dtypes(include = ["object"]).columns
  210. df_termino_materia[cols] = df_termino_materia[cols].progress_apply(elimina_tilde)
  211. # Limpieza de RIT
  212. click.echo('Limpieza de RIT')
  213. df_termino_materia['RIT'] = df_termino_materia['RIT'].progress_apply(limpia_rit)
  214. # Categorizar variables
  215. df_termino_materia['CORTE'] = df_termino_materia['CORTE'].astype('category')
  216. df_termino_materia['MOTIVO TERMINO'] = df_termino_materia['MOTIVO TERMINO'].astype('category')
  217. #Dejo solo causas Ordinarias
  218. tipo_causa = df_termino_materia[df_termino_materia['TIPO CAUSA']!='Ordinaria']
  219. df_termino_materia.drop(tipo_causa.index, axis=0, inplace=True)
  220. # Reset el index para realizar feather
  221. data.save_feather(df_termino_materia, 'clean_TerminosMateria')
  222. click.echo("Generado archivo Feather 'clean_TerminosMateria.feather'. Proceso Terminado")
  223. def carga_limpieza_ingresos_rol():
  224. df_ingresos_rol = load_concatenate_by_filename('Ingresos por Rol Penal')
  225. # Transformamos variables float64 a int16
  226. df_ingresos_rol['COD. CORTE'] = df_ingresos_rol['COD. CORTE'].fillna(0).astype(np.int16)
  227. df_ingresos_rol['COD. TRIBUNAL'] = df_ingresos_rol['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  228. df_ingresos_rol['AÑO INGRESO'] = df_ingresos_rol['AÑO INGRESO'].fillna(0).astype(np.int16)
  229. df_ingresos_rol.drop(['N°'], axis = 'columns', inplace = True)
  230. click.echo('Transformando Fechas')
  231. df_ingresos_rol['FECHA INGRESO'] = df_ingresos_rol['FECHA INGRESO'].progress_apply(convierte_fecha)
  232. click.echo('Eliminando espacios en columnas objetos')
  233. df_ingresos_rol = df_ingresos_rol.progress_apply(elimina_espacios, axis=0)
  234. click.echo('Eliminando tildes')
  235. cols = df_ingresos_rol.select_dtypes(include = ["object"]).columns
  236. df_ingresos_rol[cols] = df_ingresos_rol[cols].progress_apply(elimina_tilde)
  237. # Transformamos en variables categoricas
  238. df_ingresos_rol['CORTE'] = df_ingresos_rol['CORTE'].astype('category')
  239. # Elimina de causas que no sean del tipo ordinaria
  240. tipo_causa = df_ingresos_rol[df_ingresos_rol['TIPO CAUSA']!='Ordinaria']
  241. df_ingresos_rol.drop(tipo_causa.index, axis=0, inplace=True)
  242. data.save_feather(df_ingresos_rol,'clean_IngresosRol')
  243. click.echo("Generado archivo Feather 'clena_IngresosRol.feather'. Proceso Terminado")
  244. def carga_limpieza_terminos_rol():
  245. df_termino_rol = load_concatenate_by_filename('Términos por Rol Penal')
  246. # Elimino causas que no sean SIAGJ
  247. df_no_siagj = df_termino_rol[df_termino_rol['SISTEMA']!='SIAGJ']
  248. df_termino_rol.drop(df_no_siagj.index, axis=0, inplace=True)
  249. # Elimino filas vacias o con datos NaN
  250. df_termino_rol = df_termino_rol.dropna()
  251. df_termino_rol.drop(['N°','SISTEMA'], axis = 'columns', inplace = True)
  252. # Cambio de nombre a algunas columnas para dejarlas iguales a otros dataframes
  253. df_termino_rol.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  254. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  255. 'DURACIÓN CAUSA ':'DURACION CAUSA',
  256. 'MOTIVO DE TÉRMINO':'MOTIVO TERMINO',
  257. 'FECHA TÉRMINO':'FECHA TERMINO',
  258. 'MES TÉRMINO':'MES TERMINO',
  259. 'AÑO TÉRMINO':'AÑO TERMINO',
  260. 'TOTAL TÉRMINOS':'TOTAL TERMINOS'
  261. }, inplace = True)
  262. # Transformamos variables float64 a int16
  263. df_termino_rol['COD. CORTE'] = df_termino_rol['COD. CORTE'].fillna(0).astype(np.int16)
  264. df_termino_rol['COD. TRIBUNAL'] = df_termino_rol['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  265. df_termino_rol['DURACION CAUSA'] = df_termino_rol['DURACION CAUSA'].fillna(0).astype(np.int16)
  266. df_termino_rol['AÑO TERMINO'] = df_termino_rol['AÑO TERMINO'].fillna(0).astype(np.int16)
  267. df_termino_rol['TOTAL TERMINOS'] = df_termino_rol['TOTAL TERMINOS'].fillna(0).astype(np.int8)
  268. click.echo('Elimino tildes de las columnas object')
  269. cols = df_termino_rol.select_dtypes(include = ["object"]).columns
  270. df_termino_rol[cols] = df_termino_rol[cols].progress_apply(elimina_tilde)
  271. click.echo('Transformando fechas')
  272. df_termino_rol['FECHA INGRESO'] = df_termino_rol['FECHA INGRESO'].progress_apply(convierte_fecha)
  273. df_termino_rol['FECHA TERMINO'] = df_termino_rol['FECHA TERMINO'].progress_apply(convierte_fecha)
  274. click.echo('Elimino espacios en las columnas tipo objeto')
  275. df_termino_rol = df_termino_rol.progress_apply(elimina_espacios, axis=0)
  276. click.echo('Limpieza de RIT')
  277. df_termino_rol['RIT'] = df_termino_rol['RIT'].progress_apply(limpia_rit)
  278. # Transformamos en variables categoricas
  279. df_termino_rol['CORTE'] = df_termino_rol['CORTE'].astype('category')
  280. df_termino_rol['MOTIVO TERMINO'] = df_termino_rol['MOTIVO TERMINO'].astype('category')
  281. # Dejo solo causas Ordinarias
  282. tipo_causa = df_termino_rol[df_termino_rol['TIPO CAUSA']!='Ordinaria']
  283. df_termino_rol.drop(tipo_causa.index, axis=0, inplace=True)
  284. data.save_feather(df_termino_rol,'clean_TerminosRol')
  285. click.echo("Generado archivo Feather clean_TerminosRol.feather'. Proceso Terminado")
  286. def carga_limpieza_inventario():
  287. df_inventario = load_concatenate_by_filename('Inventario Causas en Tramitación Penal')
  288. # Elimino registros de METGE
  289. df_metge = df_inventario[df_inventario['SISTEMA']=='METGE']
  290. df_inventario.drop(df_metge.index, axis=0, inplace=True)
  291. # ESTANDARIZACION DE NOMBRES DE VARIABLES
  292. df_inventario.rename(columns = {'CÓDIGO CORTE':'COD. CORTE',
  293. 'CÓDIGO TRIBUNAL':'COD. TRIBUNAL',
  294. 'CÓDIGO MATERIA':'COD. MATERIA',
  295. ' MATERIA':'MATERIA'
  296. }, inplace = True)
  297. df_inventario.drop(['SISTEMA'], axis = 'columns', inplace = True)
  298. # TRANSFORMAMOS DE FLOAT A INTEGER
  299. df_inventario['COD. CORTE'] = df_inventario['COD. CORTE'].fillna(0).astype(np.int16)
  300. df_inventario['COD. TRIBUNAL'] = df_inventario['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  301. df_inventario['COD. MATERIA'] = df_inventario['COD. MATERIA'].fillna(0).astype(np.int16)
  302. df_inventario['TOTAL INVENTARIO'] = df_inventario['TOTAL INVENTARIO'].fillna(0).astype(np.int8)
  303. click.echo('Transformamos fechas')
  304. df_inventario['FECHA INGRESO'] = df_inventario['FECHA INGRESO'].progress_apply(convierte_fecha)
  305. df_inventario['FECHA ULT. DILIGENCIA'] = df_inventario['FECHA ULT. DILIGENCIA'].progress_apply(convierte_fecha)
  306. click.echo('Elimino espacios en las columnas tipo objetos')
  307. df_inventario = df_inventario.progress_apply(elimina_espacios, axis=0)
  308. click.echo('Elimino tildes de las columnas object')
  309. cols = df_inventario.select_dtypes(include = ["object"]).columns
  310. df_inventario[cols] = df_inventario[cols].progress_apply(elimina_tilde)
  311. # CATEGORIZACION DE VARIABLES
  312. df_inventario['CORTE'] = df_inventario['CORTE'].astype('category')
  313. df_inventario['COMPETENCIA'] = df_inventario['COMPETENCIA'].astype('category')
  314. df_inventario['TIPO ULT. DILIGENCIA'] = df_inventario['TIPO ULT. DILIGENCIA'].astype('category')
  315. # Dejo solo causas Ordinarias
  316. tipo_causa = df_inventario[df_inventario['TIPO CAUSA']!='Ordinaria']
  317. df_inventario.drop(tipo_causa.index, axis=0, inplace=True)
  318. data.save_feather(df_inventario,'clean_Inventario')
  319. click.echo("Generado archivo Feather 'clean_Inventario.feather'. Proceso Terminado")
  320. def carga_limpieza_audiencias():
  321. df_audiencias = load_concatenate_by_filename('Audiencias Realizadas Penal')
  322. df_audiencias.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  323. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  324. 'DURACIÓN AUDIENCIA':'DURACION AUDIENCIA',
  325. 'AGENDAMIENTO (DÍAS CORRIDOS)':'DIAS AGENDAMIENTO',
  326. 'DURACIÓN AUDIENCIA (MINUTOS)':'DURACION AUDIENCIA (MIN)',
  327. 'FECHA PROGRAMACIÓN AUDIENCIA':'FECHA PROGRAMACION AUDIENCIA'
  328. },
  329. inplace = True)
  330. # TRANSFORMAMOS DE FLOAT A INTEGER
  331. df_audiencias['COD. CORTE'] = df_audiencias['COD. CORTE'].fillna(0).astype(np.int16)
  332. df_audiencias['COD. TRIBUNAL'] = df_audiencias['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  333. df_audiencias['TOTAL AUDIENCIAS'] = df_audiencias['TOTAL AUDIENCIAS'].fillna(0).astype(np.int8)
  334. # Podemos observar que existen columnas que se repiten, y que tienen datos NAN en algunas pero esos datos
  335. # en otras columnas, pasa en TIPO AUDIENCIA=TIPO DE AUDIENCIA, AGENDAMIENTO (DÍAS CORRIDOS)=PLAZO AGENDAMIENTO
  336. # (DÍAS CORRIDOS), DURACIÓN AUDIENCIA (MINUTOS)= DURACIÓN AUDIENCIA
  337. df_audiencias['TIPO DE AUDIENCIA'] = df_audiencias['TIPO DE AUDIENCIA'].fillna(df_audiencias['TIPO AUDIENCIA'])
  338. df_audiencias['DIAS AGENDAMIENTO'] = df_audiencias['DIAS AGENDAMIENTO'].fillna(df_audiencias['PLAZO AGENDAMIENTO (DIAS CORRIDOS)']).astype(np.int16)
  339. df_audiencias['DURACION AUDIENCIA (MIN)'] = df_audiencias['DURACION AUDIENCIA (MIN)'].fillna(df_audiencias['DURACION AUDIENCIA'])
  340. # Elimino las columnas reemplazadas
  341. df_audiencias.drop(['TIPO AUDIENCIA','PLAZO AGENDAMIENTO (DIAS CORRIDOS)','DURACION AUDIENCIA'], axis = 'columns',
  342. inplace = True)
  343. click.echo('Transformamos fechas')
  344. df_audiencias['FECHA PROGRAMACION AUDIENCIA'] = df_audiencias['FECHA PROGRAMACION AUDIENCIA'].progress_apply(convierte_fecha)
  345. df_audiencias['FECHA AUDIENCIA'] = df_audiencias['FECHA AUDIENCIA'].progress_apply(convierte_fecha)
  346. click.echo('Elimino espacios en las columnas tipo objetos')
  347. df_audiencias = df_audiencias.progress_apply(elimina_espacios, axis=0)
  348. click.echo('Elimino tildes')
  349. cols = df_audiencias.select_dtypes(include = ["object"]).columns
  350. df_audiencias[cols] = df_audiencias[cols].progress_apply(elimina_tilde)
  351. # Categorizar
  352. df_audiencias['CORTE'] = df_audiencias['CORTE'].astype('category')
  353. # Dejo solo causas Ordinarias
  354. tipo_causa = df_audiencias[df_audiencias['TIPO CAUSA']!='Ordinaria']
  355. df_audiencias.drop(tipo_causa.index, axis=0, inplace=True)
  356. data.save_feather(df_audiencias,'clean_Audiencias')
  357. click.echo("Generado archivo Feather 'clean_Audiencias.feather'. Proceso Terminado")
  358. def carga_limpieza_duraciones():
  359. df_duraciones = load_concatenate_by_filename('Duraciones por Rol Penal')
  360. # Elimino causas que no sean SIAGJ
  361. df_no_siagj = df_duraciones[df_duraciones['SISTEMA']!='SIAGJ']
  362. df_duraciones.drop(df_no_siagj.index, axis=0, inplace=True)
  363. df_duraciones.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  364. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  365. 'DURACIÓN CAUSA ':'DURACIÓN CAUSA',
  366. 'FECHA TÉRMINO':'FECHA TERMINO',
  367. 'MOTIVO DE TÉRMINO':'MOTIVO TERMINO',
  368. 'MES TÉRMINO':'MES TERMINO',
  369. 'AÑO TÉRMINO':'AÑO TERMINO',
  370. 'TOTAL TÉRMINOS':'TOTAL TERMINOS'
  371. }, inplace = True)
  372. df_duraciones.drop(['N°','SISTEMA'], axis = 'columns', inplace = True)
  373. df_duraciones = df_duraciones.dropna()
  374. # TRANSFORMAMOS DE FLOAT A INTEGER
  375. df_duraciones['COD. CORTE'] = df_duraciones['COD. CORTE'].fillna(0).astype(np.int16)
  376. df_duraciones['COD. TRIBUNAL'] = df_duraciones['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  377. df_duraciones['AÑO TERMINO'] = df_duraciones['AÑO TERMINO'].fillna(0).astype(np.int16)
  378. df_duraciones['TOTAL TERMINOS'] = df_duraciones['TOTAL TERMINOS'].fillna(0).astype(np.int8)
  379. click.echo('Transformamos fechas')
  380. df_duraciones['FECHA INGRESO'] = df_duraciones['FECHA INGRESO'].progress_apply(convierte_fecha)
  381. df_duraciones['FECHA TERMINO'] = df_duraciones['FECHA TERMINO'].progress_apply(convierte_fecha)
  382. click.echo('Elimino espacios en las columnas tipo objetos')
  383. df_duraciones = df_duraciones.progress_apply(elimina_espacios, axis=0)
  384. click.echo('Elimino tildes')
  385. cols = df_duraciones.select_dtypes(include = ["object"]).columns
  386. df_duraciones[cols] = df_duraciones[cols].progress_apply(elimina_tilde)
  387. click.echo('Transformar el formato del RIT--AÑO a RIT-AÑO')
  388. df_duraciones['RIT'] = df_duraciones['RIT'].progress_apply(limpia_rit)
  389. # Categorizacion
  390. df_duraciones['CORTE'] = df_duraciones['CORTE'].astype('category')
  391. df_duraciones['MOTIVO TERMINO'] = df_duraciones['MOTIVO TERMINO'].astype('category')
  392. # Dejo solo causas Ordinarias
  393. tipo_causa = df_duraciones[df_duraciones['TIPO CAUSA']!='Ordinaria']
  394. df_duraciones.drop(tipo_causa.index, axis=0, inplace=True)
  395. data.save_feather(df_duraciones, 'clean_Duraciones')
  396. click.echo("Generado archivo Feather 'clean_Duraciones.feather'. Proceso Terminado")
  397. def carga_limpieza_delitos():
  398. tqdm.pandas()
  399. path_raw = "data/raw/delitos"
  400. codigos_delitos = pd.read_excel(f"{path_raw}/codigos_penal_2020.xlsx", sheet_name = "codigos vigentes", engine='openpyxl')
  401. # elimino filas con NaN
  402. codigos_delitos = codigos_delitos.drop_duplicates()
  403. # elimino 2 primeras filas que son titulos
  404. codigos_delitos = codigos_delitos.drop([0,1,2], axis = 0)
  405. # elimino columnas con datos NaN
  406. variables = range(2,248)
  407. columnas = []
  408. for variable in variables:
  409. columnas.append("Unnamed: " + str(variable))
  410. codigos_delitos = codigos_delitos.drop(columns = columnas, axis = 1)
  411. # cambio nombres columnas
  412. codigos_delitos = codigos_delitos.rename(columns = {'VERSION AL 01/01/2018':'COD. MATERIA', 'Unnamed: 1':'MATERIA'})
  413. delitos_vigentes = []
  414. for item in codigos_delitos.index:
  415. if str(codigos_delitos['COD. MATERIA'][item]).isupper():
  416. tipologia_delito=str(codigos_delitos['COD. MATERIA'][item])
  417. else:
  418. delitos_vigentes.append([codigos_delitos['COD. MATERIA'][item],
  419. str(codigos_delitos['MATERIA'][item]).upper().rstrip(),
  420. tipologia_delito,'VIGENTE'])
  421. df_delitos_vigentes = pd.DataFrame(delitos_vigentes,columns = ['COD. MATERIA','MATERIA','TIPOLOGIA MATERIA','VIGENCIA MATERIA'])
  422. click.echo('Elimino tildes de las columnas object')
  423. cols = df_delitos_vigentes.select_dtypes(include = ["object"]).columns
  424. df_delitos_vigentes[cols] = df_delitos_vigentes[cols].progress_apply(elimina_tilde)
  425. df_delitos_vigentes[cols] = df_delitos_vigentes[cols].progress_apply(limpieza_caracteres)
  426. df_delitos_vigentes['COD. MATERIA'] = df_delitos_vigentes['COD. MATERIA'].fillna(0).astype('int16')
  427. # CARGA Y LIMPIEZA DE DATOS RELACIONADOS A DELITOS NO VIGENTES
  428. codigos_delitos_novigentes = pd.read_excel(f"{path_raw}/codigos_penal_2020.xlsx", sheet_name = "Codigos no vigentes", engine='openpyxl')
  429. # cambio nombres columnas
  430. codigos_delitos_novigentes = codigos_delitos_novigentes.rename(columns = {'MATERIAS PENALES NO VIGENTES':'TIPOLOGIA MATERIA',
  431. 'Unnamed: 1':'COD. MATERIA','Unnamed: 2':'MATERIA'})
  432. # elimino primera fila que son titulos
  433. codigos_delitos_novigentes = codigos_delitos_novigentes.drop([0], axis = 0)
  434. # reemplazo Nan por ST
  435. codigos_delitos_novigentes = codigos_delitos_novigentes.fillna('ST')
  436. delitos_no_vigentes = []
  437. for item in codigos_delitos_novigentes.index:
  438. tipologia_delito = codigos_delitos_novigentes['TIPOLOGIA MATERIA'][item]
  439. if tipologia_delito != 'ST':
  440. tipologia = codigos_delitos_novigentes['TIPOLOGIA MATERIA'][item]
  441. else:
  442. tipologia_delito = tipologia
  443. delitos_no_vigentes.append([codigos_delitos_novigentes['COD. MATERIA'][item],
  444. codigos_delitos_novigentes['MATERIA'][item].rstrip(),
  445. tipologia_delito,'NO VIGENTE'])
  446. df_delitos_no_vigentes = pd.DataFrame(delitos_no_vigentes, columns = ['COD. MATERIA','MATERIA','TIPOLOGIA MATERIA','VIGENCIA MATERIA'])
  447. click.echo('Elimino tildes de las columnas object')
  448. cols = df_delitos_no_vigentes.select_dtypes(include = ["object"]).columns
  449. df_delitos_no_vigentes[cols] = df_delitos_no_vigentes[cols].progress_apply(elimina_tilde)
  450. df_delitos_no_vigentes['COD. MATERIA'] = df_delitos_no_vigentes['COD. MATERIA'].astype('int16')
  451. # UNION DE AMBOS DATASET CON DELITOS VIGENTES Y NO VIGENTES
  452. df_delitos = pd.concat([df_delitos_vigentes,df_delitos_no_vigentes])
  453. data.save_feather(df_delitos,'clean_Delitos',path='data/processed/delitos')
  454. click.echo("Generado archivo Feather 'clean_Delitos.feather'. Proceso Terminado")
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...