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 27 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
  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 elimina_tilde(str_variable):
  16. replacements = {'Á': 'A',
  17. 'É': 'E',
  18. 'Í': 'I',
  19. 'Ó': 'O',
  20. 'Ú': 'U',
  21. 'Ü': 'U',
  22. }
  23. for a, b in replacements.items():
  24. str_variable = str_variable.astype(str).str.replace(a, b)
  25. return str_variable
  26. def elimina_espacios(col):
  27. if col.dtypes == object:
  28. return (col.astype(str).str.rstrip())
  29. return col
  30. def limpia_rit(str_rit):
  31. return str_rit.replace('--','-')
  32. def limpieza_caracteres(str_col):
  33. replacements = {'-': '',
  34. '\xa0': '',
  35. '\n': ''
  36. }
  37. for a, b in replacements.items():
  38. str_col = str_col.astype(str).str.replace(a, b)
  39. return str_col
  40. def transforma_numero(str_numero):
  41. replacements = {"ún": "1",
  42. "un": "1",
  43. "dós": "2",
  44. "dos": "2",
  45. "tres": "3",
  46. "cuatro": "4",
  47. "cinco": "5",
  48. "seis": "6",
  49. "seís": "6",
  50. "séis": "6",
  51. "siete": "7",
  52. "ocho": "8",
  53. "nueve": "9",
  54. "diez": "10",
  55. "once": "11",
  56. "doce": "12",
  57. "trece": "13",
  58. "dieci": "1",
  59. "veinti": "2",
  60. "veinte": "20"
  61. }
  62. for a, b in replacements.items():
  63. str_numero = str_numero.replace(a, b)
  64. return str_numero
  65. def separa_regiones(str_region):
  66. reemplazar_region = {"DECIMA REGION": "REGION",
  67. "UNDECIMA REGION": "REGION",
  68. "DUODECIMA REGION": "REGION",
  69. "DECIMOCUARTA REGION": "REGION",
  70. "DECIMOQUINTA REGION": "REGION",
  71. "PRIMERA REGION": "REGION",
  72. "SEGUNDA REGION": "REGION",
  73. "TERCERA REGION": "REGION",
  74. "CUARTA REGION": "REGION",
  75. "QUINTA REGION": "REGION",
  76. "SEXTA REGION": "REGION",
  77. "SEPTIMA REGION": "REGION",
  78. "OCTAVA REGION": "REGION",
  79. "NOVENA REGION": "REGION",
  80. "BIOBIO": "REGION DEL BIO BIO",
  81. "AYSEN": "REGION DE AISEN",
  82. "MAGALLANES Y DE LA ANTARTICA CHILENA": "REGION DE MAGALLANES Y ANTARTICA CHILENA"
  83. }
  84. for old, new in reemplazar_region.items():
  85. str_region = str_region.replace(old, new)
  86. return str_region
  87. def transforma_asiento(str_asiento):
  88. if str_asiento.find("JUZGADO DE GARANTIA") != -1 or str_asiento.find("TRIBUNAL DE JUICIO ORAL EN LO PENAL") != -1:
  89. str_asiento = "SANTIAGO"
  90. return str_asiento
  91. def cambio_nombre_juzgados(str_tribunal):
  92. reemplazar_texto = {"1º JUZGADO DE LETRAS": "JUZGADO DE LETRAS",
  93. "6º TRIBUNAL DE JUICIO ORAL EN LO PENAL DE SAN MIGUEL": "SEXTO TRIBUNAL DE JUICIO ORAL EN LO PENAL SANTIAGO",
  94. "10º JUZGADO DE GARANTIA": "DECIMO JUZGADO DE GARANTIA",
  95. "11º JUZGADO DE GARANTIA": "UNDECIMO JUZGADO DE GARANTIA",
  96. "12º JUZGADO DE GARANTIA": "DUODECIMO JUZGADO DE GARANTIA",
  97. "13º JUZGADO DE GARANTIA": "DECIMOTERCER JUZGADO DE GARANTIA",
  98. "14º JUZGADO DE GARANTIA": "DECIMOCUARTO JUZGADO DE GARANTIA",
  99. "15º JUZGADO DE GARANTIA": "DECIMOQUINTO JUZGADO DE GARANTIA",
  100. "TRIBUNAL ORAL EN LO PENAL DE": "TRIBUNAL DE JUICIO ORAL EN LO PENAL",
  101. "1º": "PRIMER",
  102. "2º": "SEGUNDO",
  103. "3º": "TERCER",
  104. "4º": "CUARTO",
  105. "5º": "QUINTO",
  106. "6º": "SEXTO",
  107. "7º": "SEPTIMO",
  108. "8º": "OCTAVO",
  109. "9º": "NOVENO",
  110. "TRIBUNAL DE JUICIO ORAL EN LO PENAL DE DE ": "TRIBUNAL DE JUICIO ORAL EN LO PENAL ",
  111. "TRIBUNAL DE JUICIO ORAL EN LO PENAL DE": "TRIBUNAL DE JUICIO ORAL EN LO PENAL",
  112. "JUZGADO DE GARANTIA DE DE ": "JUZGADO DE GARANTIA ",
  113. "JUZGADO DE GARANTIA DE": "JUZGADO DE GARANTIA",
  114. "JUZGADO DE LETRAS Y GARANTIA DE": "JUZGADO DE LETRAS Y GARANTIA",
  115. "JUZGADO DE LETRAS DE": "JUZGADO DE LETRAS Y GARANTIA",
  116. "LA CALERA": "CALERA",
  117. "PUERTO NATALES": "NATALES",
  118. "PUERTO AYSEN": "AISEN",
  119. "PUERTO CISNES": "CISNES",
  120. "SAN VICENTE DE TAGUA-TAGUA": "SAN VICENTE",
  121. "ACHAO": "QUINCHAO",
  122. "COYHAIQUE": "COIHAIQUE"
  123. }
  124. for old, new in reemplazar_texto.items():
  125. str_tribunal = str_tribunal.replace(old, new)
  126. return str_tribunal
  127. def cambio_termino_causa(str_termino):
  128. if pd.notnull(str_termino):
  129. str_termino = str_termino.replace(".","")
  130. return str_termino
  131. def load_concatenate_by_filename(needle: str, src_path = "data/raw/pjud"):
  132. archivos = os.listdir(src_path)
  133. tqdm.pandas()
  134. dataframes = []
  135. for archivo in archivos:
  136. if archivo.find(needle) != -1:
  137. df = pd.read_csv(f"{src_path}/{archivo}", sep=";", encoding='cp850', dtype='unicode', low_memory=True)
  138. dataframes.append(df)
  139. return pd.concat(dataframes)
  140. def carga_limpieza_ingresos_materia():
  141. df_ingresos_materia = load_concatenate_by_filename('Ingresos por Materia Penal')
  142. df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'] = df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'].fillna(
  143. df_ingresos_materia['TOTAL INGRESOS POR MATERIAS(*)'])
  144. df_ingresos_materia.drop(['N°', 'TOTAL INGRESOS POR MATERIAS(*)'], axis='columns', inplace=True)
  145. df_ingresos_materia.drop([
  146. '(*)Se agregó columna total de ingresos, dado que en algunas causas, la materia se repite (error de tramitación)'],
  147. axis='columns', inplace=True)
  148. # TRANSFORMAMOS DE FLOAT A INTEGER
  149. df_ingresos_materia['COD. CORTE'] = df_ingresos_materia['COD. CORTE'].fillna(0).astype(np.int16)
  150. df_ingresos_materia['COD. TRIBUNAL'] = df_ingresos_materia['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  151. df_ingresos_materia['COD. MATERIA'] = df_ingresos_materia['COD. MATERIA'].fillna(0).astype(np.int16)
  152. df_ingresos_materia['AÑO INGRESO'] = df_ingresos_materia['AÑO INGRESO'].fillna(0).astype(np.int16)
  153. df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'] = df_ingresos_materia['TOTAL INGRESOS POR MATERIAS'].fillna(0).astype(np.int8)
  154. # Transformamos fechas
  155. click.echo('Transformando fechas')
  156. df_ingresos_materia['FECHA INGRESO'] = df_ingresos_materia['FECHA INGRESO'].progress_apply(convierte_fecha)
  157. # Elimino espacios en las columnas tipo objetos
  158. click.echo('Eliminando espacios en objetos')
  159. df_ingresos_materia = df_ingresos_materia.progress_apply(elimina_espacios, axis=0)
  160. # Elimino tildes
  161. click.echo('Eliminando tildes')
  162. cols = df_ingresos_materia.select_dtypes(include=["object"]).columns
  163. df_ingresos_materia[cols] = df_ingresos_materia[cols].progress_apply(elimina_tilde)
  164. # Categorizacion
  165. df_ingresos_materia['CORTE'] = df_ingresos_materia['CORTE'].astype('category')
  166. tipo_causa = df_ingresos_materia[df_ingresos_materia['TIPO CAUSA'] != 'Ordinaria']
  167. df_ingresos_materia.drop(tipo_causa.index, axis=0, inplace=True)
  168. data.save_feather(df_ingresos_materia, 'clean_IngresosMateria')
  169. click.echo('Generado archivo Feather. Proceso Terminado')
  170. def carga_limpieza_terminos_materia():
  171. df_termino_materia = load_concatenate_by_filename('Términos por Materia Penal')
  172. df_metge = df_termino_materia[df_termino_materia['SISTEMA']=='METGE']
  173. df_termino_materia.drop(df_metge.index, axis=0, inplace=True)
  174. # Estandarización de nombres de variables
  175. df_termino_materia.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  176. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  177. 'CÓD. MATERIA':'COD. MATERIA',
  178. 'MOTIVO DE TÉRMINO':'MOTIVO TERMINO',
  179. 'DURACIÓN CAUSA':'DURACION CAUSA',
  180. 'FECHA TÉRMINO':'FECHA TERMINO',
  181. 'MES TÉRMINO':'MES TERMINO',
  182. 'AÑO TÉRMINO':'AÑO TERMINO',
  183. 'TOTAL TÉRMINOS':'TOTAL TERMINOS'
  184. },inplace = True)
  185. df_termino_materia.drop(['N°','SISTEMA'], axis = 'columns', inplace = True)
  186. # TRANSFORMAMOS DE FLOAT A INTEGER
  187. df_termino_materia['COD. CORTE'] = df_termino_materia['COD. CORTE'].fillna(0).astype(np.int16)
  188. df_termino_materia['COD. TRIBUNAL'] = df_termino_materia['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  189. df_termino_materia['COD. MATERIA'] = df_termino_materia['COD. MATERIA'].fillna(0).astype(np.int16)
  190. df_termino_materia['DURACION CAUSA'] = df_termino_materia['DURACION CAUSA'].fillna(0).astype(np.int16)
  191. df_termino_materia['AÑO TERMINO'] = df_termino_materia['AÑO TERMINO'].fillna(0).astype(np.int16)
  192. df_termino_materia['TOTAL TERMINOS'] = df_termino_materia['TOTAL TERMINOS'].fillna(0).astype(np.int8)
  193. # Transformamos formato fecha
  194. click.echo('Convirtiendo fechas')
  195. df_termino_materia['FECHA INGRESO'] = df_termino_materia['FECHA INGRESO'].progress_apply(convierte_fecha)
  196. df_termino_materia['FECHA TERMINO'] = df_termino_materia['FECHA TERMINO'].progress_apply(convierte_fecha)
  197. # Elimino espacios en las columnas tipo objetos
  198. click.echo('Eliminando espacios')
  199. df_termino_materia = df_termino_materia.progress_apply(elimina_espacios, axis=0)
  200. # Elimino tildes de object
  201. click.echo('Eliminando tilde')
  202. cols = df_termino_materia.select_dtypes(include = ["object"]).columns
  203. df_termino_materia[cols] = df_termino_materia[cols].progress_apply(elimina_tilde)
  204. # Categorizar variables
  205. df_termino_materia['CORTE'] = df_termino_materia['CORTE'].astype('category')
  206. df_termino_materia['MOTIVO TERMINO'] = df_termino_materia['MOTIVO TERMINO'].astype('category')
  207. #Dejo solo causas Ordinarias
  208. tipo_causa = df_termino_materia[df_termino_materia['TIPO CAUSA']!='Ordinaria']
  209. df_termino_materia.drop(tipo_causa.index, axis=0, inplace=True)
  210. # Reset el index para realizar feather
  211. data.save_feather(df_termino_materia, 'clean_TerminosMateria')
  212. click.echo('Generado archivo Feather. Proceso Terminado')
  213. def carga_limpieza_ingresos_rol():
  214. df_ingresos_rol = load_concatenate_by_filename('Ingresos por Rol Penal')
  215. # Transformamos variables float64 a int16
  216. df_ingresos_rol['COD. CORTE'] = df_ingresos_rol['COD. CORTE'].fillna(0).astype(np.int16)
  217. df_ingresos_rol['COD. TRIBUNAL'] = df_ingresos_rol['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  218. df_ingresos_rol['AÑO INGRESO'] = df_ingresos_rol['AÑO INGRESO'].fillna(0).astype(np.int16)
  219. df_ingresos_rol.drop(['N°'], axis = 'columns', inplace = True)
  220. click.echo('Transformando Fechas')
  221. df_ingresos_rol['FECHA INGRESO'] = df_ingresos_rol['FECHA INGRESO'].progress_apply(convierte_fecha)
  222. click.echo('Eliminando espacios en columnas objetos')
  223. df_ingresos_rol = df_ingresos_rol.progress_apply(elimina_espacios, axis=0)
  224. click.echo('Eliminando tildes')
  225. cols = df_ingresos_rol.select_dtypes(include = ["object"]).columns
  226. df_ingresos_rol[cols] = df_ingresos_rol[cols].progress_apply(elimina_tilde)
  227. # Transformamos en variables categoricas
  228. df_ingresos_rol['CORTE'] = df_ingresos_rol['CORTE'].astype('category')
  229. # Elimina de causas que no sean del tipo ordinaria
  230. tipo_causa = df_ingresos_rol[df_ingresos_rol['TIPO CAUSA']!='Ordinaria']
  231. df_ingresos_rol.drop(tipo_causa.index, axis=0, inplace=True)
  232. data.save_feather(df_ingresos_rol,'clean_IngresosRol')
  233. click.echo('Generado archivo Feather. Proceso Terminado')
  234. def carga_limpieza_terminos_rol():
  235. df_termino_rol = load_concatenate_by_filename('Términos por Rol Penal')
  236. # Elimino causas que no sean SIAGJ
  237. df_no_siagj = df_termino_rol[df_termino_rol['SISTEMA']!='SIAGJ']
  238. df_termino_rol.drop(df_no_siagj.index, axis=0, inplace=True)
  239. # Elimino filas vacias o con datos NaN
  240. df_termino_rol = df_termino_rol.dropna()
  241. df_termino_rol.drop(['N°','SISTEMA'], axis = 'columns', inplace = True)
  242. # Cambio de nombre a algunas columnas para dejarlas iguales a otros dataframes
  243. df_termino_rol.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  244. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  245. 'DURACIÓN CAUSA ':'DURACION CAUSA',
  246. 'MOTIVO DE TÉRMINO':'MOTIVO TERMINO',
  247. 'FECHA TÉRMINO':'FECHA TERMINO',
  248. 'MES TÉRMINO':'MES TERMINO',
  249. 'AÑO TÉRMINO':'AÑO TERMINO',
  250. 'TOTAL TÉRMINOS':'TOTAL TERMINOS'
  251. }, inplace = True)
  252. # Transformamos variables float64 a int16
  253. df_termino_rol['COD. CORTE'] = df_termino_rol['COD. CORTE'].fillna(0).astype(np.int16)
  254. df_termino_rol['COD. TRIBUNAL'] = df_termino_rol['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  255. df_termino_rol['DURACION CAUSA'] = df_termino_rol['DURACION CAUSA'].fillna(0).astype(np.int16)
  256. df_termino_rol['AÑO TERMINO'] = df_termino_rol['AÑO TERMINO'].fillna(0).astype(np.int16)
  257. df_termino_rol['TOTAL TERMINOS'] = df_termino_rol['TOTAL TERMINOS'].fillna(0).astype(np.int8)
  258. click.echo('Elimino tildes de las columnas object')
  259. cols = df_termino_rol.select_dtypes(include = ["object"]).columns
  260. df_termino_rol[cols] = df_termino_rol[cols].progress_apply(elimina_tilde)
  261. click.echo('Transformando fechas')
  262. df_termino_rol['FECHA INGRESO'] = df_termino_rol['FECHA INGRESO'].progress_apply(convierte_fecha)
  263. df_termino_rol['FECHA TERMINO'] = df_termino_rol['FECHA TERMINO'].progress_apply(convierte_fecha)
  264. click.echo('Elimino espacios en las columnas tipo objeto')
  265. df_termino_rol = df_termino_rol.progress_apply(elimina_espacios, axis=0)
  266. # Transformamos en variables categoricas
  267. df_termino_rol['CORTE'] = df_termino_rol['CORTE'].astype('category')
  268. df_termino_rol['MOTIVO TERMINO'] = df_termino_rol['MOTIVO TERMINO'].astype('category')
  269. # Dejo solo causas Ordinarias
  270. tipo_causa = df_termino_rol[df_termino_rol['TIPO CAUSA']!='Ordinaria']
  271. df_termino_rol.drop(tipo_causa.index, axis=0, inplace=True)
  272. data.save_feather(df_termino_rol,'clean_TerminosRol')
  273. click.echo('Generado archivo Feather. Proceso Terminado')
  274. def carga_limpieza_inventario():
  275. df_inventario = load_concatenate_by_filename('Inventario Causas en Tramitación Penal')
  276. # Elimino registros de METGE
  277. df_metge = df_inventario[df_inventario['SISTEMA']=='METGE']
  278. df_inventario.drop(df_metge.index, axis=0, inplace=True)
  279. # ESTANDARIZACION DE NOMBRES DE VARIABLES
  280. df_inventario.rename(columns = {'CÓDIGO CORTE':'COD. CORTE',
  281. 'CÓDIGO TRIBUNAL':'COD. TRIBUNAL',
  282. 'CÓDIGO MATERIA':'COD. MATERIA',
  283. ' MATERIA':'MATERIA'
  284. }, inplace = True)
  285. df_inventario.drop(['SISTEMA'], axis = 'columns', inplace = True)
  286. # TRANSFORMAMOS DE FLOAT A INTEGER
  287. df_inventario['COD. CORTE'] = df_inventario['COD. CORTE'].fillna(0).astype(np.int16)
  288. df_inventario['COD. TRIBUNAL'] = df_inventario['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  289. df_inventario['COD. MATERIA'] = df_inventario['COD. MATERIA'].fillna(0).astype(np.int16)
  290. df_inventario['TOTAL INVENTARIO'] = df_inventario['TOTAL INVENTARIO'].fillna(0).astype(np.int8)
  291. click.echo('Transformamos fechas')
  292. df_inventario['FECHA INGRESO'] = df_inventario['FECHA INGRESO'].progress_apply(convierte_fecha)
  293. df_inventario['FECHA ULT. DILIGENCIA'] = df_inventario['FECHA ULT. DILIGENCIA'].progress_apply(convierte_fecha)
  294. click.echo('Elimino espacios en las columnas tipo objetos')
  295. df_inventario = df_inventario.progress_apply(elimina_espacios, axis=0)
  296. click.echo('Elimino tildes de las columnas object')
  297. cols = df_inventario.select_dtypes(include = ["object"]).columns
  298. df_inventario[cols] = df_inventario[cols].progress_apply(elimina_tilde)
  299. # CATEGORIZACION DE VARIABLES
  300. df_inventario['CORTE'] = df_inventario['CORTE'].astype('category')
  301. df_inventario['COMPETENCIA'] = df_inventario['COMPETENCIA'].astype('category')
  302. df_inventario['TIPO ULT. DILIGENCIA'] = df_inventario['TIPO ULT. DILIGENCIA'].astype('category')
  303. # Dejo solo causas Ordinarias
  304. tipo_causa = df_inventario[df_inventario['TIPO CAUSA']!='Ordinaria']
  305. df_inventario.drop(tipo_causa.index, axis=0, inplace=True)
  306. data.save_feather(df_inventario,'clean_Inventario')
  307. click.echo('Generado archivo Feather. Proceso Terminado')
  308. def carga_limpieza_audiencias():
  309. df_audiencias = load_concatenate_by_filename('Audiencias Realizadas Penal')
  310. df_audiencias.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  311. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  312. 'DURACIÓN AUDIENCIA':'DURACION AUDIENCIA',
  313. 'AGENDAMIENTO (DÍAS CORRIDOS)':'DIAS AGENDAMIENTO',
  314. 'DURACIÓN AUDIENCIA (MINUTOS)':'DURACION AUDIENCIA (MIN)',
  315. 'FECHA PROGRAMACIÓN AUDIENCIA':'FECHA PROGRAMACION AUDIENCIA'
  316. },
  317. inplace = True)
  318. # TRANSFORMAMOS DE FLOAT A INTEGER
  319. df_audiencias['COD. CORTE'] = df_audiencias['COD. CORTE'].fillna(0).astype(np.int16)
  320. df_audiencias['COD. TRIBUNAL'] = df_audiencias['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  321. df_audiencias['TOTAL AUDIENCIAS'] = df_audiencias['TOTAL AUDIENCIAS'].fillna(0).astype(np.int8)
  322. # Podemos observar que existen columnas que se repiten, y que tienen datos NAN en algunas pero esos datos
  323. # en otras columnas, pasa en TIPO AUDIENCIA=TIPO DE AUDIENCIA, AGENDAMIENTO (DÍAS CORRIDOS)=PLAZO AGENDAMIENTO
  324. # (DÍAS CORRIDOS), DURACIÓN AUDIENCIA (MINUTOS)= DURACIÓN AUDIENCIA
  325. df_audiencias['TIPO DE AUDIENCIA'] = df_audiencias['TIPO DE AUDIENCIA'].fillna(df_audiencias['TIPO AUDIENCIA'])
  326. df_audiencias['DIAS AGENDAMIENTO'] = df_audiencias['DIAS AGENDAMIENTO'].fillna(df_audiencias['PLAZO AGENDAMIENTO (DIAS CORRIDOS)']).astype(np.int16)
  327. df_audiencias['DURACION AUDIENCIA (MIN)'] = df_audiencias['DURACION AUDIENCIA (MIN)'].fillna(df_audiencias['DURACION AUDIENCIA'])
  328. # Elimino las columnas reemplazadas
  329. df_audiencias.drop(['TIPO AUDIENCIA','PLAZO AGENDAMIENTO (DIAS CORRIDOS)','DURACION AUDIENCIA'], axis = 'columns',
  330. inplace = True)
  331. click.echo('Transformamos fechas')
  332. df_audiencias['FECHA PROGRAMACION AUDIENCIA'] = df_audiencias['FECHA PROGRAMACION AUDIENCIA'].progress_apply(convierte_fecha)
  333. df_audiencias['FECHA AUDIENCIA'] = df_audiencias['FECHA AUDIENCIA'].progress_apply(convierte_fecha)
  334. click.echo('Elimino espacios en las columnas tipo objetos')
  335. df_audiencias = df_audiencias.progress_apply(elimina_espacios, axis=0)
  336. click.echo('Elimino tildes')
  337. cols = df_audiencias.select_dtypes(include = ["object"]).columns
  338. df_audiencias[cols] = df_audiencias[cols].progress_apply(elimina_tilde)
  339. # Categorizar
  340. df_audiencias['CORTE'] = df_audiencias['CORTE'].astype('category')
  341. # Dejo solo causas Ordinarias
  342. tipo_causa = df_audiencias[df_audiencias['TIPO CAUSA']!='Ordinaria']
  343. df_audiencias.drop(tipo_causa.index, axis=0, inplace=True)
  344. data.save_feather(df_audiencias,'clean_Audiencias')
  345. click.echo('Generado archivo Feather. Proceso Terminado')
  346. def carga_limpieza_duraciones():
  347. df_duraciones = load_concatenate_by_filename('Duraciones por Rol Penal')
  348. # Elimino causas que no sean SIAGJ
  349. df_no_siagj = df_duraciones[df_duraciones['SISTEMA']!='SIAGJ']
  350. df_duraciones.drop(df_no_siagj.index, axis=0, inplace=True)
  351. df_duraciones.rename(columns = {'CÓD. CORTE':'COD. CORTE',
  352. 'CÓD. TRIBUNAL':'COD. TRIBUNAL',
  353. 'DURACIÓN CAUSA ':'DURACIÓN CAUSA',
  354. 'FECHA TÉRMINO':'FECHA TERMINO',
  355. 'MOTIVO DE TÉRMINO':'MOTIVO TERMINO',
  356. 'MES TÉRMINO':'MES TERMINO',
  357. 'AÑO TÉRMINO':'AÑO TERMINO',
  358. 'TOTAL TÉRMINOS':'TOTAL TERMINOS'
  359. }, inplace = True)
  360. df_duraciones.drop(['N°','SISTEMA'], axis = 'columns', inplace = True)
  361. df_duraciones = df_duraciones.dropna()
  362. # TRANSFORMAMOS DE FLOAT A INTEGER
  363. df_duraciones['COD. CORTE'] = df_duraciones['COD. CORTE'].fillna(0).astype(np.int16)
  364. df_duraciones['COD. TRIBUNAL'] = df_duraciones['COD. TRIBUNAL'].fillna(0).astype(np.int16)
  365. df_duraciones['AÑO TERMINO'] = df_duraciones['AÑO TERMINO'].fillna(0).astype(np.int16)
  366. df_duraciones['TOTAL TERMINOS'] = df_duraciones['TOTAL TERMINOS'].fillna(0).astype(np.int8)
  367. click.echo('Transformamos fechas')
  368. df_duraciones['FECHA INGRESO'] = df_duraciones['FECHA INGRESO'].progress_apply(convierte_fecha)
  369. df_duraciones['FECHA TERMINO'] = df_duraciones['FECHA TERMINO'].progress_apply(convierte_fecha)
  370. click.echo('Elimino espacios en las columnas tipo objetos')
  371. df_duraciones = df_duraciones.progress_apply(elimina_espacios, axis=0)
  372. click.echo('Elimino tildes')
  373. cols = df_duraciones.select_dtypes(include = ["object"]).columns
  374. df_duraciones[cols] = df_duraciones[cols].progress_apply(elimina_tilde)
  375. click.echo('Transformar el formato del RIT--AÑO a RIT-AÑO')
  376. df_duraciones['RIT'] = df_duraciones['RIT'].progress_apply(limpia_rit)
  377. # Categorizacion
  378. df_duraciones['CORTE'] = df_duraciones['CORTE'].astype('category')
  379. df_duraciones['MOTIVO TERMINO'] = df_duraciones['MOTIVO TERMINO'].astype('category')
  380. # Dejo solo causas Ordinarias
  381. tipo_causa = df_duraciones[df_duraciones['TIPO CAUSA']!='Ordinaria']
  382. df_duraciones.drop(tipo_causa.index, axis=0, inplace=True)
  383. data.save_feather(df_duraciones, 'clean_Duraciones')
  384. click.echo('Generado archivo Feather. Proceso Terminado')
  385. def carga_limpieza_delitos():
  386. tqdm.pandas()
  387. path_raw = "data/raw/delitos"
  388. codigos_delitos = pd.read_excel(f"{path_raw}/codigos_penal_2020.xlsx", sheet_name = "codigos vigentes")
  389. # elimino filas con NaN
  390. codigos_delitos = codigos_delitos.drop_duplicates()
  391. # elimino 2 primeras filas que son titulos
  392. codigos_delitos = codigos_delitos.drop([0,1,2], axis = 0)
  393. # elimino columnas con datos NaN
  394. variables = range(2,248)
  395. columnas = []
  396. for variable in variables:
  397. columnas.append("Unnamed: " + str(variable))
  398. codigos_delitos = codigos_delitos.drop(columns = columnas, axis = 1)
  399. # cambio nombres columnas
  400. codigos_delitos = codigos_delitos.rename(columns = {'VERSION AL 01/01/2018':'COD. MATERIA', 'Unnamed: 1':'MATERIA'})
  401. delitos_vigentes = []
  402. for item in codigos_delitos.index:
  403. if str(codigos_delitos['COD. MATERIA'][item]).isupper():
  404. tipologia_delito=str(codigos_delitos['COD. MATERIA'][item])
  405. else:
  406. delitos_vigentes.append([codigos_delitos['COD. MATERIA'][item],
  407. str(codigos_delitos['MATERIA'][item]).upper().rstrip(),
  408. tipologia_delito,'VIGENTE'])
  409. df_delitos_vigentes = pd.DataFrame(delitos_vigentes,columns = ['COD. MATERIA','MATERIA','TIPOLOGIA MATERIA','VIGENCIA MATERIA'])
  410. click.echo('Elimino tildes de las columnas object')
  411. cols = df_delitos_vigentes.select_dtypes(include = ["object"]).columns
  412. df_delitos_vigentes[cols] = df_delitos_vigentes[cols].progress_apply(elimina_tilde)
  413. df_delitos_vigentes[cols] = df_delitos_vigentes[cols].progress_apply(limpieza_caracteres)
  414. df_delitos_vigentes['COD. MATERIA'] = df_delitos_vigentes['COD. MATERIA'].fillna(0).astype('int16')
  415. # CARGA Y LIMPIEZA DE DATOS RELACIONADOS A DELITOS NO VIGENTES
  416. codigos_delitos_novigentes = pd.read_excel(f"{path_raw}/codigos_penal_2020.xlsx", sheet_name = "Codigos no vigentes")
  417. # cambio nombres columnas
  418. codigos_delitos_novigentes = codigos_delitos_novigentes.rename(columns = {'MATERIAS PENALES NO VIGENTES':'TIPOLOGIA MATERIA',
  419. 'Unnamed: 1':'COD. MATERIA','Unnamed: 2':'MATERIA'})
  420. # elimino primera fila que son titulos
  421. codigos_delitos_novigentes = codigos_delitos_novigentes.drop([0], axis = 0)
  422. # reemplazo Nan por ST
  423. codigos_delitos_novigentes = codigos_delitos_novigentes.fillna('ST')
  424. delitos_no_vigentes = []
  425. for item in codigos_delitos_novigentes.index:
  426. tipologia_delito = codigos_delitos_novigentes['TIPOLOGIA MATERIA'][item]
  427. if tipologia_delito != 'ST':
  428. tipologia = codigos_delitos_novigentes['TIPOLOGIA MATERIA'][item]
  429. else:
  430. tipologia_delito = tipologia
  431. delitos_no_vigentes.append([codigos_delitos_novigentes['COD. MATERIA'][item],
  432. codigos_delitos_novigentes['MATERIA'][item].rstrip(),
  433. tipologia_delito,'NO VIGENTE'])
  434. df_delitos_no_vigentes = pd.DataFrame(delitos_no_vigentes, columns = ['COD. MATERIA','MATERIA','TIPOLOGIA MATERIA','VIGENCIA MATERIA'])
  435. click.echo('Elimino tildes de las columnas object')
  436. cols = df_delitos_no_vigentes.select_dtypes(include = ["object"]).columns
  437. df_delitos_no_vigentes[cols] = df_delitos_no_vigentes[cols].progress_apply(elimina_tilde)
  438. df_delitos_no_vigentes['COD. MATERIA'] = df_delitos_no_vigentes['COD. MATERIA'].astype('int16')
  439. # UNION DE AMBOS DATASET CON DELITOS VIGENTES Y NO VIGENTES
  440. df_delitos = pd.concat([df_delitos_vigentes,df_delitos_no_vigentes])
  441. data.save_feather(df_delitos,'clean_Delitos',path='data/processed/delitos')
  442. click.echo('Generado archivo Feather. Proceso Terminado')
Tip!

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

Comments

Loading...