├── Clase 5 ├── data │ ├── Listado de cursos - Facultad de Ciencias Sociales_files │ │ ├── cta-loaded.js │ │ ├── saved_resource │ │ ├── facebook-footer.jpg │ │ ├── saved_resource.html │ │ ├── 8698515(1).js │ │ ├── wp-embed.min.js │ │ ├── dropit.css │ │ ├── jquery.matchHeight-min.js │ │ ├── jquery.fitvids.js │ │ ├── dropit.js │ │ ├── hotjar-2444127.js │ │ ├── jquery-migrate.min.js │ │ ├── wp-emoji-release.min.js │ │ ├── current.js │ │ └── fac_ciencias_sociales.svg │ └── world-happiness-report-2023-countries.csv ├── Ejemplo_API.ipynb ├── 3.webscrapping.ipynb └── 2.Visualizacion_de_datos_2.ipynb ├── img ├── lsts.png ├── wlong.png ├── arraysn.png ├── sunat.jpeg ├── joinimages.png ├── db_example.jpeg └── estructuras.png ├── Github ├── img │ ├── gh.png │ ├── esquema.jpeg │ ├── branch_main.png │ ├── create_repo.png │ ├── phdcomics.png │ ├── simple_git.png │ ├── create_repo1.png │ ├── create_repo2.png │ ├── create_repo3.png │ └── version_control_drive.png └── README.md ├── Clase 1 └── img │ └── focalizacion.png ├── .ipynb_checkpoints └── Untitled-checkpoint.ipynb ├── Clase 3 ├── datos │ └── pbi.csv ├── Módulos_y_paquetes.ipynb └── Manejo_BD_ii.ipynb ├── Clase 4 ├── datos │ └── pbi.csv ├── Manejo_BD_iii.ipynb └── Manejo_BD_ii.ipynb └── README.md /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/cta-loaded.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/saved_resource: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img/lsts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/img/lsts.png -------------------------------------------------------------------------------- /img/wlong.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/img/wlong.png -------------------------------------------------------------------------------- /img/arraysn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/img/arraysn.png -------------------------------------------------------------------------------- /img/sunat.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/img/sunat.jpeg -------------------------------------------------------------------------------- /Github/img/gh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/gh.png -------------------------------------------------------------------------------- /img/joinimages.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/img/joinimages.png -------------------------------------------------------------------------------- /img/db_example.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/img/db_example.jpeg -------------------------------------------------------------------------------- /img/estructuras.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/img/estructuras.png -------------------------------------------------------------------------------- /Github/img/esquema.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/esquema.jpeg -------------------------------------------------------------------------------- /Github/img/branch_main.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/branch_main.png -------------------------------------------------------------------------------- /Github/img/create_repo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/create_repo.png -------------------------------------------------------------------------------- /Github/img/phdcomics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/phdcomics.png -------------------------------------------------------------------------------- /Github/img/simple_git.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/simple_git.png -------------------------------------------------------------------------------- /Clase 1/img/focalizacion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Clase 1/img/focalizacion.png -------------------------------------------------------------------------------- /Github/img/create_repo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/create_repo1.png -------------------------------------------------------------------------------- /Github/img/create_repo2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/create_repo2.png -------------------------------------------------------------------------------- /Github/img/create_repo3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/create_repo3.png -------------------------------------------------------------------------------- /Github/img/version_control_drive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Github/img/version_control_drive.png -------------------------------------------------------------------------------- /.ipynb_checkpoints/Untitled-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/facebook-footer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccsuehara/python_para_las_ccss/HEAD/Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/facebook-footer.jpg -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/saved_resource.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/8698515(1).js: -------------------------------------------------------------------------------- 1 | var _hsp=window._hsp=window._hsp||[];_hsp.push(['addEnabledFeatureGates',[]]);!function(t,e,r){if(!document.getElementById(t)){var n=document.createElement("script");for(var a in n.src="https://js.hs-banner.com/v2/8698515/banner.js",n.type="text/javascript",n.id=t,r)r.hasOwnProperty(a)&&n.setAttribute(a,r[a]);var i=document.getElementsByTagName("script")[0];i.parentNode.insertBefore(n,i)}}("cookieBanner-8698515",0,{"data-cookieconsent":"ignore","data-hs-ignore":true,"data-loader":"hs-scriptloader","data-hsjs-portal":8698515,"data-hsjs-env":"prod","data-hsjs-hublet":"na1"});!function(e,t){if(!document.getElementById(e)){var c=document.createElement("script");c.src="https://js.hs-analytics.net/analytics/1704992400000/8698515.js",c.type="text/javascript",c.id=e;var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(c,n)}}("hs-analytics"); -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/wp-embed.min.js: -------------------------------------------------------------------------------- 1 | /*! This file is auto-generated */ 2 | !function(c,d){"use strict";var e=!1,n=!1;if(d.querySelector)if(c.addEventListener)e=!0;if(c.wp=c.wp||{},!c.wp.receiveEmbedMessage)if(c.wp.receiveEmbedMessage=function(e){var t=e.data;if(t)if(t.secret||t.message||t.value)if(!/[^a-zA-Z0-9]/.test(t.secret)){for(var r,a,i,s=d.querySelectorAll('iframe[data-secret="'+t.secret+'"]'),n=d.querySelectorAll('blockquote[data-secret="'+t.secret+'"]'),o=0;o=Math.floor(Math.abs(b-k))?c[c.length-1]=l.add(a):c.push(a);b=k});return c},h=function(a){return parseFloat(a)||0},b=d.fn.matchHeight=function(a){if("remove"===a){var f=this;this.css("height","");d.each(b._groups,function(a,b){b.elements=b.elements.not(f)});return this}if(1>=this.length)return this;a="undefined"!== 7 | typeof a?a:!0;b._groups.push({elements:this,byRow:a});b._apply(this,a);return this};b._groups=[];b._throttle=80;b._maintainScroll=!1;b._beforeUpdate=null;b._afterUpdate=null;b._apply=function(a,f){var c=d(a),e=[c],k=d(window).scrollTop(),l=d("html").outerHeight(!0),g=c.parents().filter(":hidden");g.css("display","block");f&&(c.each(function(){var a=d(this),b="inline-block"===a.css("display")?"inline-block":"block";a.data("style-cache",a.attr("style"));a.css({display:b,"padding-top":"0","padding-bottom":"0", 8 | "margin-top":"0","margin-bottom":"0","border-top-width":"0","border-bottom-width":"0",height:"100px"})}),e=n(c),c.each(function(){var a=d(this);a.attr("style",a.data("style-cache")||"").css("height","")}));d.each(e,function(a,b){var c=d(b),e=0;f&&1>=c.length||(c.each(function(){var a=d(this),b="inline-block"===a.css("display")?"inline-block":"block";a.css({display:b,height:""});a.outerHeight(!1)>e&&(e=a.outerHeight(!1));a.css("display","")}),c.each(function(){var a=d(this),b=0;"border-box"!==a.css("box-sizing")&& 9 | (b+=h(a.css("border-top-width"))+h(a.css("border-bottom-width")),b+=h(a.css("padding-top"))+h(a.css("padding-bottom")));a.css("height",e-b)}))});g.css("display","");b._maintainScroll&&d(window).scrollTop(k/l*d("html").outerHeight(!0));return this};b._applyDataApi=function(){var a={};d("[data-match-height], [data-mh]").each(function(){var b=d(this),c=b.attr("data-match-height")||b.attr("data-mh");a[c]=c in a?a[c].add(b):b});d.each(a,function(){this.matchHeight(!0)})};var m=function(a){b._beforeUpdate&& 10 | b._beforeUpdate(a,b._groups);d.each(b._groups,function(){b._apply(this.elements,this.byRow)});b._afterUpdate&&b._afterUpdate(a,b._groups)};b._update=function(a,f){if(f&&"resize"===f.type){var c=d(window).width();if(c===g)return;g=c}a?-1===e&&(e=setTimeout(function(){m(f);e=-1},b._throttle)):m(f)};d(b._applyDataApi);d(window).bind("load",function(a){b._update(!1,a)});d(window).bind("resize orientationchange",function(a){b._update(!0,a)})})(jQuery); -------------------------------------------------------------------------------- /Clase 3/datos/pbi.csv: -------------------------------------------------------------------------------- 1 | Anio,Amazonas,Áncash,Apurímac,Arequipa,Ayacucho,Cajamarca,Cusco,Huancavelica,Huánuco,Ica,Junín,La Libertad,Lambayeque,Lima,Prov. Const. del Callao,Región Lima,Provincia de Lima,Loreto,Madre de Dios,Moquegua,Pasco,Piura,Puno,San Martín,Tacna,Tumbes,Ucayali 2 | 2007,1778775,15672771,1824181,16991831,2975676,8159499,10913725,2475279,3200861,8793956,9240435,14615612,6880023,136238703,13386423,11404858,111447422,6910964,1864543,7525100,5486459,12651720,5888474,3266254,5143137,1637185,3054659 3 | 2008,1930947,16854588,1688564,18885807,3401175,9319769,11663686,2613850,3464132,10415637,10023855,15653801,7512522,148415981,14627416,12488983,121299582,7324982,1902177,8663619,5416732,13580502,6328455,3598432,5016741,1902059,3212843 4 | 2009,2058318,16400826,1623801,19032479,3750401,10050467,13631820,2696095,3499798,10841974,9039077,15716171,7910362,148910138,14288888,11612252,123008998,7374935,2033411,8436303,5040946,13998851,6587873,3740600,4823192,2082047,3243767 5 | 2010,2210682,16013215,1765744,20158733,3922514,10140905,15405459,2817536,3739082,11607992,9518659,16624855,8449884,164623842,15689336,12300019,136634487,7906943,2229180,8457008,4702403,15106528,6980479,4034361,5338879,2307874,3351315 6 | 2011,2287107,16155687,1869417,21038813,4111349,10595497,17384466,2909215,3955589,12883432,10009485,17378414,8937792,178742876,17563803,13562753,147616320,7608889,2454999,7785269,4641887,16366999,7384505,4245537,5466509,2168906,3548168 7 | 2012,2551601,17666947,2110908,22033542,4482971,11270583,17711332,3143661,4380310,13067505,10718558,18712792,9782672,189597321,18070083,13897097,157630141,8212422,1950139,7756800,4880072,17066135,7734458,4752177,5526840,2440755,3882453 8 | 2013,2682266,18478843,2342674,22629103,4906299,11086928,20708699,3174927,4642728,14394675,11095514,19532083,10138533,200400691,19196199,14893394,166311098,8505693,2240082,8598669,4885819,17746782,8294320,4828116,5781849,2491026,3947464 9 | 2014,2824603,16028265,2437434,22773308,4879476,10855588,20723581,3281748,4799787,14809397,12391582,19821258,10354938,208022491,19828477,15468191,172725823,8779305,1923155,8371348,5046668,18750443,8487313,5173301,6094038,2607186,3957775 10 | 2015,2782128,17584621,2630345,23524592,5162331,10798612,21071852,3265820,5114983,15295581,14412891,20274733,10809529,214469326,20209052,15992567,178267707,8584514,2346810,8693747,5211406,18866671,8519702,5466266,6598403,2540855,4163474 11 | 2016,2784366,18365696,6343065,29623112,5177917,10581305,21898270,3212948,5345445,15325191,14285221,20448345,11080412,220241329,20690862,16146749,183403718,7602217,2663699,8635514,5329324,18924869,9075999,5588107,6506248,2507255,4176645 12 | 2017,2940822,19317454,7718535,30724797,5451854,10901682,21576717,3354985,5832171,16206741,14954057,20797558,11371483,224691974,21400320,16285655,187005999,8087444,2409050,8696704,5333755,18473111,9434737,5944145,6584715,2649033,4305190 13 | 2018,3118373,20712339,7131314,31506818,5760202,11209419,21700735,3525421,6010056,16994391,15459518,21840178,11837862,234445543,22229310,17183773,195032460,8932782,2255653,8785457,5337612,19758433,9666999,6063316,7110940,2752958,4440780 14 | 2019,3168990,20059093,7170478,31404343,5931518,11479756,22006880,3527812,6081484,17656354,15330366,22637274,12113549,240498497,22458010,17316831,200723656,9336037,2124983,8416846,5443881,20626256,9803780,6081464,8737472,2919599,4625127 -------------------------------------------------------------------------------- /Clase 4/datos/pbi.csv: -------------------------------------------------------------------------------- 1 | Anio,Amazonas,Áncash,Apurímac,Arequipa,Ayacucho,Cajamarca,Cusco,Huancavelica,Huánuco,Ica,Junín,La Libertad,Lambayeque,Lima,Prov. Const. del Callao,Región Lima,Provincia de Lima,Loreto,Madre de Dios,Moquegua,Pasco,Piura,Puno,San Martín,Tacna,Tumbes,Ucayali 2 | 2007,1778775,15672771,1824181,16991831,2975676,8159499,10913725,2475279,3200861,8793956,9240435,14615612,6880023,136238703,13386423,11404858,111447422,6910964,1864543,7525100,5486459,12651720,5888474,3266254,5143137,1637185,3054659 3 | 2008,1930947,16854588,1688564,18885807,3401175,9319769,11663686,2613850,3464132,10415637,10023855,15653801,7512522,148415981,14627416,12488983,121299582,7324982,1902177,8663619,5416732,13580502,6328455,3598432,5016741,1902059,3212843 4 | 2009,2058318,16400826,1623801,19032479,3750401,10050467,13631820,2696095,3499798,10841974,9039077,15716171,7910362,148910138,14288888,11612252,123008998,7374935,2033411,8436303,5040946,13998851,6587873,3740600,4823192,2082047,3243767 5 | 2010,2210682,16013215,1765744,20158733,3922514,10140905,15405459,2817536,3739082,11607992,9518659,16624855,8449884,164623842,15689336,12300019,136634487,7906943,2229180,8457008,4702403,15106528,6980479,4034361,5338879,2307874,3351315 6 | 2011,2287107,16155687,1869417,21038813,4111349,10595497,17384466,2909215,3955589,12883432,10009485,17378414,8937792,178742876,17563803,13562753,147616320,7608889,2454999,7785269,4641887,16366999,7384505,4245537,5466509,2168906,3548168 7 | 2012,2551601,17666947,2110908,22033542,4482971,11270583,17711332,3143661,4380310,13067505,10718558,18712792,9782672,189597321,18070083,13897097,157630141,8212422,1950139,7756800,4880072,17066135,7734458,4752177,5526840,2440755,3882453 8 | 2013,2682266,18478843,2342674,22629103,4906299,11086928,20708699,3174927,4642728,14394675,11095514,19532083,10138533,200400691,19196199,14893394,166311098,8505693,2240082,8598669,4885819,17746782,8294320,4828116,5781849,2491026,3947464 9 | 2014,2824603,16028265,2437434,22773308,4879476,10855588,20723581,3281748,4799787,14809397,12391582,19821258,10354938,208022491,19828477,15468191,172725823,8779305,1923155,8371348,5046668,18750443,8487313,5173301,6094038,2607186,3957775 10 | 2015,2782128,17584621,2630345,23524592,5162331,10798612,21071852,3265820,5114983,15295581,14412891,20274733,10809529,214469326,20209052,15992567,178267707,8584514,2346810,8693747,5211406,18866671,8519702,5466266,6598403,2540855,4163474 11 | 2016,2784366,18365696,6343065,29623112,5177917,10581305,21898270,3212948,5345445,15325191,14285221,20448345,11080412,220241329,20690862,16146749,183403718,7602217,2663699,8635514,5329324,18924869,9075999,5588107,6506248,2507255,4176645 12 | 2017,2940822,19317454,7718535,30724797,5451854,10901682,21576717,3354985,5832171,16206741,14954057,20797558,11371483,224691974,21400320,16285655,187005999,8087444,2409050,8696704,5333755,18473111,9434737,5944145,6584715,2649033,4305190 13 | 2018,3118373,20712339,7131314,31506818,5760202,11209419,21700735,3525421,6010056,16994391,15459518,21840178,11837862,234445543,22229310,17183773,195032460,8932782,2255653,8785457,5337612,19758433,9666999,6063316,7110940,2752958,4440780 14 | 2019,3168990,20059093,7170478,31404343,5931518,11479756,22006880,3527812,6081484,17656354,15330366,22637274,12113549,240498497,22458010,17316831,200723656,9336037,2124983,8416846,5443881,20626256,9803780,6081464,8737472,2919599,4625127 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 1. Información General 2 | 3 | Nombre del curso : Fundamentos de Python para las Ciencias Sociales 4 | Profesora del curso : Carla Solis Uehara 5 | Correo electrónico PUCP : csolisu@pucp.edu.pe 6 | Horario de clases : 7 | - 04/01/2025: 8am - 12pm 8 | - 06/01/2025: 7pm - 10pm 9 | - 07/01/2025: 7pm - 10pm 10 | - 09/01/2025: 7pm - 10pm 11 | - 11/01/2025: 8am - 11am 12 | 13 | 14 | ## 2. Justificación 15 | La importancia de este curso radica en la creciente importancia de la programación como habilidad fundamental en el mundo digital actual. Python, como un lenguaje de programación versátil y fácil de aprender, se ha convertido en una opción popular para principiantes y profesionales por igual. Por tanto, este curso está diseñado para proporcionar una comprensión fundamental del lenguaje de programación Python. Está destinado a estudiantes con poca o ninguna experiencia en programación que estén interesados en aprender Python para el análisis de datos, la computación científica, el desarrollo web o cualquier otra aplicación. El curso cubrirá los conceptos básicos de la sintaxis y la semántica de Python, así como aplicaciones fundamentales en data science. 16 | 17 | 18 | 19 | ## 3. Resultados de aprendizaje 20 | 21 | - Identifica elementos y conceptos básicos de programación. 22 | - Aplica los diferentes tipos de datos de Python, incluidas listas, diccionarios y tuplas. 23 | - Escribe programas simples en Python en la resolución de problemas. 24 | - Maneja las bibliotecas y módulos de Python para realizar tareas como análisis de datos y computación científica. 25 | - Aplica Python para interactuar con las API web y raspar páginas web. 26 | - Aplica la herramienta Github. 27 | 28 | ## 4. Contenido del Curso: 29 | 30 | Introducción a python 31 | ● Python como lenguaje de programación 32 | ● Configuración de un entorno de programación 33 | ● Sintaxis básica y tipos de datos (string, integer, float, boolean) 34 | ● Variables y asignación 35 | ● Operadores básicos (aritméticos, comparación, lógicos) 36 | ● Inputs y outputs básicos 37 | 38 | Estructuras de control 39 | ● sentencias if-else 40 | ● for loops 41 | ● while loops 42 | ● break y continue 43 | ● manejo de errores y excepciones 44 | 45 | Funciones 46 | ● Definir y llamar funciones 47 | ● Parámetros y argumentos 48 | ● Valor de retorno 49 | ● Scope 50 | 51 | Estructuras de datos 52 | ● Listas 53 | ● Tuplas 54 | ● Diccionarios 55 | ● Sets 56 | 57 | Trabajando con archivos 58 | ● Leer y escribir archivos 59 | ● Tipos de datos: tabular, json 60 | 61 | Módulos y paquetes 62 | ● Importar y exportar módulos 63 | ● Instalación y uso de paquetes 64 | 65 | Introducción a la ciencia de datos 66 | ● Obtener datos 67 | o Web-scrapping 68 | o APIs 69 | ● Trabajar con datos 70 | o Pandas 71 | o Visualización de datos 72 | o Análisis geoespacial 73 | 74 | Git 75 | ● Usar git como herramienta de control de cambios 76 | 77 | 78 | ## 5. Evaluación 79 | La evaluación consistirá en dos tareas y un trabajo final. El peso total de cada uno de los componentes será el siguiente: 80 | 81 | |Evaluación| Peso| 82 | | ----------- | ----------- | 83 | |Tareas (2)| 60% | 84 | |Trabajo final (1) | 40% | 85 | 86 | 87 | Las y los estudiantes tendrán la posibilidad de presentar las tareas después de fecha, sin embargo, se aplicará una penalidad del 15% sobre la nota final de la tarea por cada día que pase. 88 | 89 | ## 6. Bibliografía 90 | - Downey, A. (2015). Think Python: How to Think Like a Computer Scientist (2nd ed.). O'Reilly Media. 91 | - VanderPlas, J. (2016). Python Data Science Handbook. O'Reilly Media. 92 | - Matthes, E. (2016). Python crash course: A hands – on, project-based introduction to programming (2nd ed.). No Starch Press 93 | - Sweigart, A. (2015). Automate the Boring Stuff with Python: Practical Programming for Total Beginners. No Starch Press. 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/jquery.fitvids.js: -------------------------------------------------------------------------------- 1 | /*jshint browser:true */ 2 | /*! 3 | * FitVids 1.1 4 | * 5 | * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com 6 | * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ 7 | * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ 8 | * 9 | */ 10 | 11 | ;(function( $ ){ 12 | 13 | 'use strict'; 14 | 15 | $.fn.fitVids = function( options ) { 16 | var settings = { 17 | customSelector: null, 18 | ignore: null 19 | }; 20 | 21 | if(!document.getElementById('fit-vids-style')) { 22 | // appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js 23 | var head = document.head || document.getElementsByTagName('head')[0]; 24 | var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}'; 25 | var div = document.createElement("div"); 26 | div.innerHTML = '

x

'; 27 | head.appendChild(div.childNodes[1]); 28 | } 29 | 30 | if ( options ) { 31 | $.extend( settings, options ); 32 | } 33 | 34 | return this.each(function(){ 35 | var selectors = [ 36 | 'iframe[src*="player.vimeo.com"]', 37 | 'iframe[src*="youtube.com"]', 38 | 'iframe[src*="youtube-nocookie.com"]', 39 | 'iframe[src*="kickstarter.com"][src*="video.html"]', 40 | 'iframe[src*="facebook.com"]', 41 | 'object', 42 | 'embed' 43 | ]; 44 | 45 | if (settings.customSelector) { 46 | selectors.push(settings.customSelector); 47 | } 48 | 49 | var ignoreList = '.fitvidsignore'; 50 | 51 | if(settings.ignore) { 52 | ignoreList = ignoreList + ', ' + settings.ignore; 53 | } 54 | 55 | var $allVideos = $(this).find(selectors.join(',')); 56 | $allVideos = $allVideos.not('object object'); // SwfObj conflict patch 57 | $allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video. 58 | 59 | $allVideos.each(function(){ 60 | var $this = $(this); 61 | if($this.parents(ignoreList).length > 0) { 62 | return; // Disable FitVids on this video. 63 | } 64 | if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; } 65 | if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width')))) 66 | { 67 | $this.attr('height', 9); 68 | $this.attr('width', 16); 69 | } 70 | var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(), 71 | width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(), 72 | aspectRatio = height / width; 73 | if(!$this.attr('name')){ 74 | var videoName = 'fitvid' + $.fn.fitVids._count; 75 | $this.attr('name', videoName); 76 | $.fn.fitVids._count++; 77 | } 78 | $this.wrap('
').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+'%'); 79 | $this.removeAttr('height').removeAttr('width'); 80 | }); 81 | }); 82 | }; 83 | 84 | // Internal counter for unique video names. 85 | $.fn.fitVids._count = 0; 86 | 87 | // Works with either jQuery or Zepto 88 | })( window.jQuery || window.Zepto ); -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/dropit.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Dropit v1.1.0 3 | * http://dev7studios.com/dropit 4 | * 5 | * Copyright 2012, Dev7studios 6 | * Free to use and abuse under the MIT license. 7 | * http://www.opensource.org/licenses/mit-license.php 8 | */ 9 | 10 | ;(function($) { 11 | 12 | $.fn.dropit = function(method) { 13 | 14 | var methods = { 15 | 16 | init : function(options) { 17 | this.dropit.settings = $.extend({}, this.dropit.defaults, options); 18 | return this.each(function() { 19 | var $el = $(this), 20 | el = this, 21 | settings = $.fn.dropit.settings; 22 | 23 | // Hide initial submenus 24 | $el.addClass('dropit') 25 | .find('>'+ settings.triggerParentEl +':has('+ settings.submenuEl +')').addClass('dropit-trigger') 26 | .find(settings.submenuEl).addClass('dropit-submenu').hide(); 27 | 28 | // Open on click 29 | $el.off(settings.action).on(settings.action, settings.triggerParentEl +':has('+ settings.submenuEl +') > '+ settings.triggerEl +'', function(){ 30 | // Close click menu's if clicked again 31 | if(settings.action == 'click' && $(this).parents(settings.triggerParentEl).hasClass('dropit-open')){ 32 | settings.beforeHide.call(this); 33 | $(this).parents(settings.triggerParentEl).removeClass('dropit-open').find(settings.submenuEl).hide(); 34 | settings.afterHide.call(this); 35 | return false; 36 | } 37 | 38 | // Hide open menus 39 | settings.beforeHide.call(this); 40 | $('.dropit-open').removeClass('dropit-open').find('.dropit-submenu').hide(); 41 | settings.afterHide.call(this); 42 | 43 | // Open this menu 44 | settings.beforeShow.call(this); 45 | $(this).parents(settings.triggerParentEl).addClass('dropit-open').find(settings.submenuEl).show(); 46 | settings.afterShow.call(this); 47 | 48 | return false; 49 | }); 50 | 51 | // Close if outside click 52 | $(document).on('click', function(){ 53 | settings.beforeHide.call(this); 54 | $('.dropit-open').removeClass('dropit-open').find('.dropit-submenu').hide(); 55 | settings.afterHide.call(this); 56 | }); 57 | 58 | // If hover 59 | if(settings.action == 'mouseenter'){ 60 | $el.on('mouseleave', '.dropit-open', function(){ 61 | settings.beforeHide.call(this); 62 | $(this).removeClass('dropit-open').find(settings.submenuEl).hide(); 63 | settings.afterHide.call(this); 64 | }); 65 | } 66 | 67 | settings.afterLoad.call(this); 68 | }); 69 | } 70 | 71 | }; 72 | 73 | if (methods[method]) { 74 | return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 75 | } else if (typeof method === 'object' || !method) { 76 | return methods.init.apply(this, arguments); 77 | } else { 78 | $.error( 'Method "' + method + '" does not exist in dropit plugin!'); 79 | } 80 | 81 | }; 82 | 83 | $.fn.dropit.defaults = { 84 | action: 'click', // The open action for the trigger 85 | submenuEl: 'ul', // The submenu element 86 | triggerEl: 'a', // The trigger element 87 | triggerParentEl: 'li', // The trigger parent element 88 | afterLoad: function(){}, // Triggers when plugin has loaded 89 | beforeShow: function(){}, // Triggers before submenu is shown 90 | afterShow: function(){}, // Triggers after submenu is shown 91 | beforeHide: function(){}, // Triggers before submenu is hidden 92 | afterHide: function(){} // Triggers before submenu is hidden 93 | }; 94 | 95 | $.fn.dropit.settings = {}; 96 | 97 | })(jQuery); 98 | -------------------------------------------------------------------------------- /Clase 5/Ejemplo_API.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "3c541e5e", 6 | "metadata": {}, 7 | "source": [ 8 | "# Un ejemplo de API\n" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "id": "e9a59e74", 14 | "metadata": {}, 15 | "source": [ 16 | "Para la clase de APIS, vámonos al siguiente notebook: \n", 17 | "\n", 18 | "https://github.com/worldbank/dec-python-course/blob/main/1-foundations/4-api-and-dataviz/foundations-s4-api.ipynb\n", 19 | "\n", 20 | "\n", 21 | "Créditos: Este material fue hecho por el equipo de DEC den Banco Mundial. En especial gracias a [Luise San Martín](https://github.com/luisesanmartin) por la creación del material." 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 2, 27 | "id": "9aba50c5", 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [ 31 | "#Api del BCR\n", 32 | "import requests\n", 33 | "import pandas as pd\n", 34 | "import json" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 10, 40 | "id": "ed155fef", 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "cod = [\"PN38706PM\", \"PN38707PM\"]\n", 45 | "\n", 46 | "url = \"https://estadisticas.bcrp.gob.pe/estadisticas/series/api/\"" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 11, 52 | "id": "96ad3b24", 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "import pandas as pd\n", 57 | "import requests" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 12, 63 | "id": "cc153eb5", 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "class APIBCRP:\n", 68 | " \"\"\"api manager que hace querys al bcrp\"\"\"\n", 69 | " \n", 70 | " def __init__(self, url, code_s, format):\n", 71 | " # falta implementar rangos y convertir a dataframe. \n", 72 | " \n", 73 | " self.code_s = code_s\n", 74 | " self.all_codes = self.make_query()\n", 75 | " self.url = f\"{url}/{self.all_codes}/{format}\"\n", 76 | " self.data = self.download()\n", 77 | " print(self.url)\n", 78 | " \n", 79 | "\n", 80 | " def make_query(self):\n", 81 | " codes = ''\n", 82 | " for i, code in enumerate(self.code_s):\n", 83 | " if i < len(self.code_s) - 1:\n", 84 | " codes += f\"{code}-\"\n", 85 | " else:\n", 86 | " codes += f\"{code}\"\n", 87 | " return codes\n", 88 | " \n", 89 | " def download(self):\n", 90 | " try:\n", 91 | " response = requests.get(self.url)\n", 92 | " response.raise_for_status()\n", 93 | " print(\"datos descargados\")\n", 94 | " except requests.RequestException as e:\n", 95 | " print(f\"No hubo rpta: {e}\")\n", 96 | " return response.json()\n", 97 | " \n", 98 | "\n" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 13, 104 | "id": "aa3339f6", 105 | "metadata": {}, 106 | "outputs": [ 107 | { 108 | "name": "stdout", 109 | "output_type": "stream", 110 | "text": [ 111 | "datos descargados\n", 112 | "https://estadisticas.bcrp.gob.pe/estadisticas/series/api//PN38706PM-PN38707PM/json\n" 113 | ] 114 | } 115 | ], 116 | "source": [ 117 | "obj = APIBCRP(url, cod, \"json\")" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": 14, 123 | "id": "3de2e0d1", 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "lista_fechas = []\n", 128 | "lista_valores = []\n", 129 | "\n", 130 | "for elem in obj.data['periods']:\n", 131 | " lista_fechas.append(elem['name'])\n", 132 | " lista_valores.append(elem['values'][0])\n", 133 | "\n" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": 15, 139 | "id": "126eb93f", 140 | "metadata": {}, 141 | "outputs": [], 142 | "source": [ 143 | "\n", 144 | "df = pd.DataFrame()\n", 145 | "df['fecha'] = lista_fechas\n", 146 | "df['valores'] = lista_valores\n" 147 | ] 148 | } 149 | ], 150 | "metadata": { 151 | "kernelspec": { 152 | "display_name": "strmlt", 153 | "language": "python", 154 | "name": "python3" 155 | }, 156 | "language_info": { 157 | "codemirror_mode": { 158 | "name": "ipython", 159 | "version": 3 160 | }, 161 | "file_extension": ".py", 162 | "mimetype": "text/x-python", 163 | "name": "python", 164 | "nbconvert_exporter": "python", 165 | "pygments_lexer": "ipython3", 166 | "version": "3.12.3" 167 | } 168 | }, 169 | "nbformat": 4, 170 | "nbformat_minor": 5 171 | } 172 | -------------------------------------------------------------------------------- /Clase 4/Manejo_BD_iii.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "vscode": { 7 | "languageId": "plaintext" 8 | } 9 | }, 10 | "source": [ 11 | "# Manejo de bases de datos para las ciencias sociales III" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "metadata": {}, 17 | "source": [ 18 | "### Juntar datos (merge)\n", 19 | "\n", 20 | "A veces tenemos los datos que nos interesan, esparcidos en diferentes dataframes. \n", 21 | "1er paso para hacer la unión de datos: Identificar el identificador único!\n" 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "metadata": {}, 27 | "source": [ 28 | "\n", 29 | "La sintaxis más general de un merge es la siguiente: \n", 30 | "\n", 31 | "``` python\n", 32 | "pd.merge(left = left_df,\n", 33 | " right=right_df,\n", 34 | " left_on=colname, \n", 35 | " right_on=colname,\n", 36 | " how=merge_type)\n", 37 | "\n", 38 | "```\n", 39 | "\n", 40 | "El merge_type (o tipo de merge puede ser):\n", 41 | "\n", 42 | "- left: quedan todas las observaciones (por keys) de las mano izquierda\n", 43 | "- right: quedan todas las observaciones (por keys) de la mano derecha\n", 44 | "- outer: es la unión de los keys de ambas bases\n", 45 | "- inner: es la intersección de los keys de ambas bases. " 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 21, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "\n", 55 | "import pandas as pd\n", 56 | "\n", 57 | "## Leyendo los archivos. \n", 58 | "locacion_datos = \"aqui coloca el string con la locación de tus datos\"\n", 59 | "locacion_datos = \"/Users/ccsuehara/Downloads/Datos_abiertos_admision_2021_1_2024_1.csv\" # este es el mio\n", 60 | "df = pd.read_csv(locacion_datos)\n", 61 | "pbi = pd.read_csv(\"datos/pbi.csv\")\n", 62 | "\n", 63 | "def str_replace(txt):\n", 64 | " return txt.replace(\"á\", \"a\").replace(\"é\", \"e\").replace(\"í\", \"i\").replace(\n", 65 | " \"ó\", \"o\").replace(\"ú\", \"u\").replace(\"Á\", \"A\").replace('Prov. Const. del Callao', 'Callao')" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 25, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "df['DOMICILIO_DEPA'] = df['DOMICILIO_DEPA'].str.title()\n", 75 | "pbi_long = pbi.melt(id_vars=\"Anio\", var_name = \"departamento\", value_name = \"pbi\")\n", 76 | "\n", 77 | "df['DOMICILIO_DEPA'] = df['DOMICILIO_DEPA'].apply(str_replace)\n", 78 | "pbi_long['departamento'] = pbi_long['departamento'].apply(str_replace)\n", 79 | "\n", 80 | "pbi_2019 = pbi_long[pbi_long['Anio'] == 2019]" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "lst = df['DOMICILIO_DEPA'].unique()\n", 90 | "\n", 91 | "lst.sort()\n", 92 | "lst" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [ 101 | "pbi_long['departamento'].unique().sort()\n", 102 | "lst2 = pbi_long['departamento'].unique()\n", 103 | "lst2.sort()\n", 104 | "lst2" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "metadata": {}, 111 | "outputs": [], 112 | "source": [ 113 | "pd.merge(df, pbi_2019,\n", 114 | " left_on = 'DOMICILIO_DEPA',\n", 115 | " right_on = 'departamento'\n", 116 | " #, how = 'left'\n", 117 | " )\n", 118 | "\n" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "metadata": {}, 124 | "source": [ 125 | "### Guardando los datos\n", 126 | "\n", 127 | "Finalmente, guardamos los datos en un archivo de nuestra elección. Así como los métodos de lectura de archivos, existe una variedad de tipos de archivos a los que podemos guardar nuestros datos. En este caso, guardaremos los datos en un archivo CSV." 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "df.to_csv(\"datos_procesados.csv\")" 137 | ] 138 | } 139 | ], 140 | "metadata": { 141 | "kernelspec": { 142 | "display_name": "strmlt", 143 | "language": "python", 144 | "name": "python3" 145 | }, 146 | "language_info": { 147 | "codemirror_mode": { 148 | "name": "ipython", 149 | "version": 3 150 | }, 151 | "file_extension": ".py", 152 | "mimetype": "text/x-python", 153 | "name": "python", 154 | "nbconvert_exporter": "python", 155 | "pygments_lexer": "ipython3", 156 | "version": "3.12.3" 157 | } 158 | }, 159 | "nbformat": 4, 160 | "nbformat_minor": 2 161 | } 162 | -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/hotjar-2444127.js: -------------------------------------------------------------------------------- 1 | window.hjSiteSettings = window.hjSiteSettings || {"site_id":2444127,"r":0.15925122767857144,"rec_value":0.23500000000000001,"state_change_listen_mode":"automatic","record":false,"continuous_capture_enabled":true,"recording_capture_keystrokes":true,"session_capture_console_consent":false,"anonymize_digits":true,"anonymize_emails":true,"suppress_all":false,"suppress_all_on_specific_pages":[],"suppress_text":false,"suppress_location":false,"user_attributes_enabled":false,"legal_name":"","privacy_policy_url":"","deferred_page_contents":[],"record_targeting_rules":[],"feedback_widgets":[],"heatmaps":[],"polls":[],"integrations":{"optimizely":{"tag_recordings":false},"abtasty":{"tag_recordings":false},"mixpanel":{"send_events":false},"unbounce":{"tag_recordings":false},"google_optimize":{"tag_recordings":false},"hubspot":{"enabled":false,"send_recordings":false,"send_surveys":false}},"features":["feedback.widgetV2","survey.image_question","ask.popover_redesign","error_reporting","survey.type_button","client_script.compression.pc","feedback.embeddable_widget","heatmap.continuous.manual_retaker","survey.embeddable_widget","survey.screenshots","settings.billing_v2"],"tracking_code_verified":true}; 2 | 3 | !function(){"use strict";function e(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:10,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),this.send=e,this.batchSize=r,this.flushInterval=n,this.buffer=[],this.flushTimer=null}var r,n;return r=t,(n=[{key:"getBuffer",value:function(){return this.buffer}},{key:"add",value:function(e){var t=this;this.buffer.push(e),this.buffer.length>=this.batchSize?this.flush():this.flushTimer||(this.flushTimer=setTimeout((function(){t.flush()}),this.flushInterval))}},{key:"flush",value:function(){this.buffer.length>0&&(this.send(this.buffer),this.buffer=[]),this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}}])&&e(r.prototype,n),t}();function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function i(e){for(var t=1;t0&&h(o)){var v={name:e,type:"distribution",value:Math.round(g),tags:d({tag:r,extraTags:a})};s.add(v)}return c}catch(t){console.debug("Failed to send timer metric: ",{name:e,tag:r,error:t})}},timeIncr:function(e,t){var r,n,i,a,s=t.tag,o=t.start,c=t.flush,d=t.extraTags,h=t.type,g=hj.metrics.time(),v=o&&g?g-o:void 0,m=(r=e,{tagName:n=f(s),start:(a=(i=u.loggedMetrics[r])&&i[n]||{}).start,total:a.total}),w=v?v+(m.total||0):m.total;return l(e,m.tagName,{total:w}),c&&b.timeEnd(e,{tag:s,total:w,extraTags:d,type:h}),w},timeWatcher:function(){var e,t=0,r=!1,n=function(){var r,n=b.time();return t+=null!==(r=e&&n&&n-e)&&void 0!==r?r:0,e=b.time(),t};return{start:function(){if(!r)return r=!0,e=b.time()},incr:n,end:function(){var r=n();return t=0,e=void 0,r}}},getErrorMessage:function(e){return e instanceof Error?e.message:"string"==typeof e?e:""}};window.hj=window.hj||function(){for(var e=arguments.length,t=new Array(e),r=0;r");t!==e&&T(e)!==T(t)&&u("HTML tags must be properly nested and closed: "+e)}var O=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,q=s.htmlPrefilter;s.UNSAFE_restoreLegacyHtmlPrefilter=function(){s.htmlPrefilter=function(e){return P(e),e.replace(O,"<$1>")}},s.htmlPrefilter=function(e){return P(e),q(e)};var D,_=s.fn.offset;s.fn.offset=function(){var e=this[0];return!e||e.nodeType&&e.getBoundingClientRect?_.apply(this,arguments):(u("jQuery.fn.offset() requires a valid DOM element"),arguments.length?this:void 0)},s.ajax&&(D=s.param,s.param=function(e,t){var r=s.ajaxSettings&&s.ajaxSettings.traditional;return void 0===t&&r&&(u("jQuery.param() no longer uses jQuery.ajaxSettings.traditional"),t=r),D.call(this,e,t)});var E,F,J=s.fn.andSelf||s.fn.addBack;return s.fn.andSelf=function(){return u("jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()"),J.apply(this,arguments)},s.Deferred&&(E=s.Deferred,F=[["resolve","done",s.Callbacks("once memory"),s.Callbacks("once memory"),"resolved"],["reject","fail",s.Callbacks("once memory"),s.Callbacks("once memory"),"rejected"],["notify","progress",s.Callbacks("memory"),s.Callbacks("memory")]],s.Deferred=function(e){var i=E(),a=i.promise();return i.pipe=a.pipe=function(){var o=arguments;return u("deferred.pipe() is deprecated"),s.Deferred(function(n){s.each(F,function(e,t){var r="function"==typeof o[e]&&o[e];i[t[1]](function(){var e=r&&r.apply(this,arguments);e&&"function"==typeof e.promise?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[t[0]+"With"](this===a?n.promise():this,r?[e]:arguments)})}),o=null}).promise()},e&&e.call(i,i),i},s.Deferred.exceptionHook=E.exceptionHook),s}); 3 | -------------------------------------------------------------------------------- /Github/README.md: -------------------------------------------------------------------------------- 1 | # Introducción a Python para las CCSS 2 | ## Sesión 0 : Cómo utilizar Github [1](#myfootnote1) 3 | 4 | 1 Este material se basa fuertemente en los entrenamientos de [DIME](https://github.com/worldbank/dime-github-trainings), del World Bank. Gracias por la licencia MIT! 5 | (Y gracias a Alexander Quispe por el incentivo ahacer esta intro a github!) 6 | 7 | 8 | ### Antes de empezar, verifica tener lo siguiente: 9 | 10 | 1. Cuenta en Github https://github.com/join (Bonus: cualquier email educativo @edu / @edu.pe permite obtener una cuenta pro https://github.com/education). 11 | 2. Mandar tu nombre de usuario a csolisu@pucp.edu.pe. 12 | 3. Tener instalado Github Desktop https://github.com/apps/desktop. 13 | 4. Iniciar sesión en Github Desktop con tu cuenta creada. 14 | 5. Recibir invitación del repo https://github.com/ccsuehara/letras_2025_0 y haber aceptado. 15 | 7. Tener un editor de texto instalado. 16 | 7.1 En windows, puede ser notepad, en mac, el textedit 17 | 18 | 19 | ### Cómo usar Github 20 | 21 | Objetivos de aprendizaje: 22 | 23 | Como observador: 24 | 25 | - Explorar un proyecto de Github y ver en qué contribuyen los otros miembros. 26 | 27 | Como contribuidor: 28 | - Personal 29 | - Crear mis propios repos para trabajar en mis proyectos. 30 | - Realizar cambios y mejoras, y poder subir estos cambios. 31 | 32 | - Equipo: 33 | - Descargar un repo de Github y poder trabajar con él. 34 | - Crear un espacio en el repo del proyecto en el que tú puedas trabajar. 35 | - Realizar cambios y mejoras al proyecto, y poder subir esos cambios. 36 | 37 | 38 | ## ¿Qué es Git y Github? 39 | 40 | ### Git 41 | Git es una herramienta muy utilizada en el mundo de la informática para gestionar código. Es especialmente buena para la colaboración, pero también resulta muy útil en proyectos de una sola persona. En los primeros tiempos de Git, uno tenía que gestionar su propio repositorio de código a través de la línea de comandos y configurar sus propios servidores para compartir el código, pero ahora existen varias soluciones basadas en la nube con interfaces no técnicas. GitHub es la más utilizada en la comunidad de investigación. Otras implementaciones de Git que se utilizan habitualmente son GitLab y Bitbucket. Dado que todas se basan en Git, comparten la mayoría de las funciones y, si aprende una de ellas, sus habilidades se pueden transferir a otra. 42 | 43 | ### Github 44 | GitHub tiene herramientas que ofrecen alternativas menos técnicas a la hora de interactuar con la funcionalidad de Git y esa es probablemente la razón por la que GitHub es la implementación de Git más popular en la comunidad de investigación. El principal inconveniente de GitHub es que no se pueden crear repositorios de código privados utilizando la cuenta gratuita (pero se puede recibir una invitación). GitLab, por ejemplo, te permite crear repositorios privados en una cuenta gratuita, pero debes usar la línea de comandos para contribuir con el código. Hemos creado recursos y proporcionamos enlaces a recursos externos adicionales para GitHub en nuestra página Primeros pasos con GitHub. 45 | 46 | [Source](https://dimewiki.worldbank.org/Data_Management) 47 | 48 | 49 | Viéndolo esquemáticamente: 50 | 51 | drawing 52 | 53 | [Source](https://github.com/worldbank/DIME-Resources/blob/master/git-1-intro.pdf) 54 | 55 | 56 | ### ¿Qué es un contribuidor? 57 | 58 | >> Básicamente alguien que contribuye con código a un repositorio (repo). 59 | Entiende y sigue instrucciones del administrador del repo. 60 | 61 | - Github contribuye a solucionar el problema del "Documento_Final.docx". 62 | 63 | drawing 64 | 65 | - E inclusive del "Documento_final_final_finalísimo.docx" 66 | 67 | - Nuestra solución común es llamar al documento 68 | - Paper_for_review_csu_200321.docx 69 | - Paper_for_review_csu_200321_ae_comments.docx 70 | 71 | - Github trackea no solo las iniciales y la hora, sino cada edición hecha al documento. 72 | 73 | >> OJO: github no lee archivos binarios (o archivos que no sean puro texto). 74 | 75 | - Github también soluciona: 76 | - Problemas de copia conflictiva (Dropbox, etc) 77 | - No puedo reproducir los resultados de mi tesis 78 | - Quién escribió esto hace muchos años 79 | 80 | Los conceptos que manejaremos hoy son 3: 81 | 82 | ## 0. Repositorio Git 83 | 84 | Un repositorio es el elemento más básico de GitHub. Es un lugar donde puedes almacenar el código, los archivos y el historial de revisiones de cada archivo. Los repositorios pueden contar con múltiples colaboradores y pueden ser públicos como privados. 85 | 86 | 87 | ### Creando un repo 88 | 89 | Usualmente, Github servirá para almacenar proyectos individuales. Crearemos un repo en el que podremos guardar nuestro proyecto final. 90 | 91 | 1. Ve a la página principal de Github. Dale click al botón verde que dice *New* 92 | 93 | drawing 94 | 95 | 2. Luego, elige el nombre del repo. 96 | Tambien tenemos otras opciones, como agregar una descripción del repo, volverlo público/privado, agregarle un .gitignore, un README.md, y una licencia. Creen el repositorio! 97 | 98 | drawing 99 | 100 | 3. Una vez creado el repo, te dan las siguientes instrucciones. Dale click a *Set up in Desktop* 101 | 102 | drawing 103 | 104 | 4. Aparecerá el siguiente cuadro, acepten 105 | 106 | drawing 107 | 108 | 5. Finalmente, github les pedirá que elijan la carpeta asociada al repo. **No elegir una carpeta que esté en Dropbox, Box, etc** !. 109 | 110 | ### ¿Qué guardar en un repo? 111 | Lo más recomendable es almacenar **solamente** archivos de código. Archivos de datos (bases de datos, pdfs, etc) idealmente deberían ir en otro folder. 112 | 113 | ## 1. Commit 114 | 115 | - ¿Qué es un control de versiones? 116 | 117 | Por ejemplo, miremos al control de versiones que tiene un google doc: 118 | 119 | drawing 120 | 121 | Todas las versiones de este documento están almacenadas. Se pueden ver los cambios que hizo cada contribuidora al documento. Sin embargo, Google docs almacena la totalidad de todas las versiones! 122 | 123 | Para no tener que guardar todas estas versiones, Git **usa los commits para indicar las differencias significativas entre versión y versión** 124 | 125 | Cada commit es una captura de los archivos del proyecto en determinado momento, y lo compara respecto al commit anterior. 126 | 127 | Cada commit tiene un timestamp (dentro de este ya tiene un id que incluye fecha y hora) 128 | 129 | #### ¿Cómo hacer un commit ? 130 | 131 | 0. Crear .txt llamado lyrics en mi nuevo repo y lo guardé. Abre el tab de cambios (changes) en Github Desktop. 132 | Github desktop se ha dado cuenta que hay nuevos cambios a tu repo. 133 | 1. Sigue los siguientes 4 pasos para hacer commit: 134 | 1. Asegúrate de que tus cambios estén marcados. 135 | 2. Escribe un mensaje de commit. 136 | 3. Haz click en el boton de commit. 137 | 4. Finalmente, haz un git push. 138 | 139 | 140 | ### Checkea tu commit en Github 141 | 142 | Ve a https://github.com/nombredeusuario/nombrederepo/network 143 | - Ves tu commit ? 144 | 145 | Ve a https://github.com/nombredeusuario/nombrederepo/commits 146 | 147 | #### ¿Qué es un git push? 148 | - El git push es la acción de subir los cambios del repo local al repo remoto, de manera que ambos se sincronizan. 149 | 150 | ## 2. Clone (clonar) 151 | 152 | Clonar es similar a descargar un repositorio. 153 | La diferencia entre clonar y descargar es que **Github recuerda de dónde descargamos el repositorio**. Esto es necesario para saber a dónde mandar nuestros cambios cuando seamos contribuidores. 154 | 155 | ### Cómo clonar un repo 156 | 1. Ve a https://github.com/ccsuehara/python_para_las_ccss 157 | 2. Haz click en el botón verde que dice *Code* 158 | 3. Dale click en *Open with Github Desktop* 159 | 4. Selecciona la carpeta de tu computadora donde se clonará el repo. **NO** lo clones en una carpeta compartida de Dropbox, Box, etc. 160 | 161 | Finalmente, explora el folder clonado! Compáralo con lo que viste en Github. 162 | 163 | Cada vez que haya una actualización en el repo del curso, puedes hacer un git pull de los nuevos cambios. 164 | 165 | #### ¿Qué es un git pull? 166 | - El git pull es la acción de subir los cambios del repo remoto al repo local, de manera que ambos se sincronizan. 167 | 168 | 169 | 170 | 6. Listo, ya tienes un folder asociado a un repo en tu computadora. Intenta hacer tu primer commit y verifica que 171 | 172 | OJO: NO OLVIDAR DE HACER COMMIT CONSTANTEMENTE A SU TRABAJO 173 | OJO 2: NO OLVIDAR SINCRONIZAR DESPUES DE HACER COMMIT! 174 | 175 | 176 | 177 | ## Adicionales 178 | 179 | ## 4.Adicional: Branch 180 | 181 | 182 | - Los branches son la propiedad "killer"/genial de Git. Esto hace a Git una herramienta poderosa de colaboración y no solo de control de versiones. 183 | 184 | - Los branches **permiten crear una copia del código donde puedes experimentar/jugar/desarrollar** con él. Si te gusta el resultado, **puedes mergear el experimento a la versión principal**. 185 | 186 | - Esta versión no-lineal es más fidedigna a cómo se trabaja en la vida real. 187 | 188 | drawing 189 | 190 | ## Explorando branches 191 | 192 | ¿Puedes cambiar la rama en */commits*, qué sucede cuando cambias la rama allí ? 193 | 194 | Cual es la versión clonada en tu computadora? Cuando se clona un repo **todas las versiones** son clonadas, pero **solo una** es la que se muestra en nuestra carpeta. 195 | 196 | Haz la prueba de cambiar la rama, en https://github.com/ccsuehara/letras_2025_0/, ¿cambia acaso el contenido? 197 | 198 | 199 | Un flujo de trabajo típico en Git implica tener varias ramas. Hay otras herramientas en Github que vuelve este flujo de trabajo muy manejable, sin embargo, está fuera del alcance de hoy. 200 | 201 | ## Creando una branch 202 | 203 | - Ve a https://github.com/ccsuehara/letras_2025_0, y dale click al botón que dice (símbolo branch) main. **Asegúrate que sea el main!!!** 204 | 205 | - Escribe tu nombre "nombre_apellido" en el cuadro de diálogo y dale click para crear la branch. 206 | 207 | ## Combinando el commit y el branch 208 | 209 | ### ¡Ahora quiero que colabores en el repo de la clase! 210 | 211 | 1. Asegúrate de que tu rama aparezca en GitHub Desktop. Sitúate en ella. Esto significa que esta rama está checkeada (checked out). 212 | 213 | 2. Abre un editor de texto. 214 | 3. Googlea la letra de tu canción favorita y cópiala en el editor de texto que acabas de abrir. 215 | 4. Guarda el archivo en formato *.txt* con el nombre tunombre_cancion. 216 | 217 | 218 | ## Pull requests 219 | 220 | Una propiedad adicional a los branches es el **pull request** 221 | Cuando las ediciones que hiciste están listas para ser mergeadas con el *main*, puedes hacer un pull request, lo cual integrará tus ediciones en la rama *main*. 222 | 223 | ### OJO: por favor no aceptes tu mism@ el merge pull. Yo lo haré. 224 | 225 | Es común que el acceso a la rama *main* solo la tenga el repo maintainer (no todos los contribuidores). 226 | 227 | - Ve a https://github.com/ccsuehara/letras_2025_0/pulls y dale click a *New pull request* 228 | - Asegúrate de que la branch *main* esté seleccionada como *base:* branch. 229 | - Selecciona tu branch como *compare:* branch 230 | - Scrollea para ver que tus ediciones son las que quieres que se integren con la main branch, dale click a *Create pull request* 231 | 232 | 233 |

234 | ## Otros recursos de aprendizaje: 235 | 236 | ### Aprender Github desde el command line/ línea de comandos: 237 | 238 | - En este tutorial, hemos visto los elementos esenciales para utilizar Github, sin embargo, hay una forma de usar Github desde la consola. Aquí hay una lista de referencias en caso quieran explorar más este uso. 239 | 240 | https://education.github.com/git-cheat-sheet-education.pdf 241 | 242 | 243 | 244 | -------------------------------------------------------------------------------- /Clase 5/2.Visualizacion_de_datos_2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import pandas as pd\n", 10 | "import altair as alt\n", 11 | "import wbgapi as wb" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": null, 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "#pip install wbgapi" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "happy_all = pd.read_csv(\"./data/world-happiness-report-2023.csv\")\n", 30 | "happy_23 = pd.read_csv(\"./data/world-happiness-report-2023-countries.csv\")\n", 31 | "happy_21 = pd.read_csv(\"./data/world-happiness-report-2021.csv\")\n", 32 | "\n", 33 | "happy = pd.merge(happy_all[happy_all['year'] == 2022],\n", 34 | " happy_21[['Country name', \"Regional indicator\" ]],\n", 35 | " on = \"Country name\",\n", 36 | " how = \"inner\",\n", 37 | " indicator = True)" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "\n", 47 | "alt.themes.enable('urbaninstitute')\n", 48 | "#latimes\n", 49 | "#ggplot2\n", 50 | "\n", 51 | "# Definir un tema, más sobre esto: \n", 52 | "#https://towardsdatascience.com/consistently-beautiful-visualizations-with-altair-themes-c7f9f889602\n", 53 | "def tema_graf():\n", 54 | " font = \"Helvetica\"\n", 55 | " labelFont = \"Garamond\"\n", 56 | " sourceFont = \"Calibri\"\n", 57 | " \n", 58 | " return {\n", 59 | " \"config\" : {\n", 60 | " \"title\": {'font': font, \n", 61 | " 'fontSize': 15,\n", 62 | " 'fontWeight': 300,\n", 63 | " 'offset':0,\n", 64 | " 'anchor':'left'\n", 65 | " },\n", 66 | " \"axis\": {\n", 67 | " \"labelFont\": font,\n", 68 | " \"titleFont\": font,\n", 69 | " \"domainColor\": \"gray\"\n", 70 | " },\n", 71 | " \"header\": {\n", 72 | " \"labelFont\": font,\n", 73 | " \"titleFont\": font\n", 74 | " },\n", 75 | " \"legend\": {\n", 76 | " \"labelFont\": labelFont,\n", 77 | " \"titleFont\": labelFont,\n", 78 | " \"symbolType\": 'circle',\n", 79 | " \"padding\": 1\n", 80 | " \n", 81 | " }\n", 82 | " ,\n", 83 | " 'background': '#47e6e6' \n", 84 | " }\n", 85 | " }\n", 86 | "\n", 87 | "# alt.themes.register('mitema', tema_graf)\n", 88 | "# alt.themes.enable('mitema')" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "# Poniendo título a nuestro gráfico \n", 98 | "alt.Chart(happy, height = 300, width = 500).mark_point().encode(\n", 99 | " x = alt.X(\"Life Ladder:Q\"),\n", 100 | " y = alt.Y(\"Log GDP per capita:Q\", scale = alt.Scale()),\n", 101 | " color = alt.Color(\"Regional indicator\"),\n", 102 | " size = alt.Size('Generosity')\n", 103 | " ).interactive().properties(\n", 104 | "title = {\n", 105 | " 'text': [\"Esto parece un gráfico inspirado en Rosling\"],\n", 106 | " 'subtitle': [\"Es un homenaje\",\n", 107 | " \"Fuente: Happiness Report\"],\n", 108 | " \"color\": \"Black\",\n", 109 | " \"subtitleColor\": \"Red\"\n", 110 | "}\n", 111 | ")\n" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "#Cambiando los titulos de los ejes\n", 121 | "\n", 122 | "alt.Chart(happy, height = 300, width = 500).mark_point().encode(\n", 123 | " x = alt.X(\"Life Ladder:Q\", title = \"índice de felicidad\"),\n", 124 | " y = alt.Y(\"Log GDP per capita:Q\", title = \"PBi per capita (logs)\"),\n", 125 | " color = alt.Color(\"Regional indicator\"),\n", 126 | " size = alt.Size('Generosity')\n", 127 | " ).interactive().properties(\n", 128 | " title={\n", 129 | " \"text\": [\"Esto parece un gráfico inspirado en Rosling\"], \n", 130 | " \"subtitle\": [\"Es un homenaje\",\n", 131 | " \"Fuente: Happiness Report\"],\n", 132 | " \"color\": \"Black\",\n", 133 | " \"subtitleColor\": \"Red\"\n", 134 | " })" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": null, 140 | "metadata": {}, 141 | "outputs": [], 142 | "source": [ 143 | "#Cambiando los titulos de los ejes\n", 144 | "## Para ver los palettes disponibles https://vega.github.io/vega/docs/schemes/\n", 145 | "alt.Chart(happy).mark_point().encode(\n", 146 | " x = alt.X(\"Life Ladder:Q\", title = \"índice de felicidad\"),\n", 147 | " y = alt.Y(\"Log GDP per capita:Q\" , title = \"PBi per capita (logs)\"),\n", 148 | " color = alt.Color(\"Regional indicator\"),\n", 149 | " size = alt.Size('Generosity')\n", 150 | " ).interactive().properties(\n", 151 | " title={\n", 152 | " \"text\": [\"Esto parece un gráfico inspirado en Rosling\"], \n", 153 | " \"subtitle\": [\"Es un homenaje\",\n", 154 | " \"Fuente: Happiness Report\"],\n", 155 | " \"color\": \"Black\",\n", 156 | " \"subtitleColor\": \"Red\"\n", 157 | " })" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "#happy_peru = happy_all[happy_all['Country name'] == 'Peru']" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "metadata": {}, 173 | "outputs": [], 174 | "source": [ 175 | "import wbgapi as wb" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": null, 181 | "metadata": {}, 182 | "outputs": [], 183 | "source": [ 184 | "wb.source.info()" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "\n", 194 | "\n", 195 | "tbl2 = wb.data.DataFrame('EN.ATM.CO2E.PC',\n", 196 | " time = range(2000, 2020), labels = True)\n", 197 | "\n", 198 | "tbl2" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "## Usando la api para descargar información del Banco mundial\n", 208 | "## pip install wbgapi\n", 209 | "## si no puedes usar pip, prueba hacer conda install pip\n", 210 | "## Fuente: https://stackoverflow.com/questions/41060382/using-pip-to-install-packages-to-anaconda-environment\n", 211 | "\n", 212 | "tbl = wb.data.DataFrame('SP.POP.TOTL',\n", 213 | " time = range(2000, 2020), labels = True)\n", 214 | "\n", 215 | "tbl = tbl.reset_index()\n", 216 | "\n", 217 | "tbl.rename(columns = {'SP.POP.TOTL': 'poblacion'}, inplace = True)\n", 218 | "\n", 219 | "\n", 220 | "lst = wb.economy.info().table()\n", 221 | "lst.pop()\n", 222 | "nombres = pd.DataFrame(data = lst,\n", 223 | " columns = [\"economy\", \"Country\", \"Region\", \"income_classification\"])\n", 224 | "\n", 225 | "\n", 226 | "tbl_f = pd.merge(tbl,\n", 227 | " nombres,\n", 228 | " on = [\"economy\", \"Country\"],\n", 229 | " how = \"inner\")" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "tbl_f = tbl_f.loc[tbl_f['Region'] != '']\n", 239 | "\n" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": null, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "tbl_melt = tbl_f.melt(id_vars = ['economy', 'Country', 'Region', 'income_classification'],\n", 249 | " value_vars = [col for col in tbl if col.startswith('YR')])" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "##[col for col in tbl if col.startswith('YR')]\n", 259 | "# lst_vacia = []\n", 260 | "# for col in tbl:\n", 261 | "# if col.startswith('YR'):\n", 262 | "# lst_vacia.append(col)\n", 263 | "# lst_vacia\n", 264 | "tbl_melt\n", 265 | " \n", 266 | " " 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "metadata": {}, 273 | "outputs": [], 274 | "source": [ 275 | "tbl_melt['year'] = tbl_melt['variable'].str.replace('YR', '').astype('int')\n", 276 | "\n", 277 | "tbl_melt.head(10)" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": null, 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "\n", 287 | "## agregaciones, y otros gráficos\n", 288 | "\n", 289 | "g1 = alt.Chart(tbl_melt).mark_area().encode(\n", 290 | " x=\"year\",\n", 291 | " y=\"sum(value):Q\",\n", 292 | " color=\"Region:N\"\n", 293 | ")\n", 294 | "\n", 295 | "g1" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": null, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "peru = tbl_melt.loc[tbl_melt['Country'] == 'Peru']\n", 305 | "peru.head()" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": null, 311 | "metadata": {}, 312 | "outputs": [], 313 | "source": [ 314 | "g2 = alt.Chart(tbl_melt).mark_bar().encode(\n", 315 | " x = alt.X(\"year\"),\n", 316 | " y=\"value:Q\",\n", 317 | " color = alt.condition(\n", 318 | " alt.datum.year == 2005,\n", 319 | " alt.value(\"red\"),\n", 320 | " alt.value(\"blue\")\n", 321 | " )\n", 322 | ")\n", 323 | "\n", 324 | "\n", 325 | " \n", 326 | "g2" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": null, 332 | "metadata": {}, 333 | "outputs": [], 334 | "source": [ 335 | "g3 = alt.Chart(tbl_melt).mark_area().encode(\n", 336 | " x='year:Q',\n", 337 | " y='sum(value):Q',\n", 338 | " color='Region:N',\n", 339 | " row = alt.Row('Region:N')\n", 340 | ").properties(height=30, width=300)\n", 341 | "\n", 342 | "g3" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": null, 348 | "metadata": {}, 349 | "outputs": [], 350 | "source": [ 351 | "alt.hconcat(g1, g2)" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": null, 357 | "metadata": {}, 358 | "outputs": [], 359 | "source": [ 360 | "alt.vconcat(alt.hconcat(g1, g2), g3)" 361 | ] 362 | } 363 | ], 364 | "metadata": { 365 | "kernelspec": { 366 | "display_name": "Python 3 (ipykernel)", 367 | "language": "python", 368 | "name": "python3" 369 | }, 370 | "language_info": { 371 | "codemirror_mode": { 372 | "name": "ipython", 373 | "version": 3 374 | }, 375 | "file_extension": ".py", 376 | "mimetype": "text/x-python", 377 | "name": "python", 378 | "nbconvert_exporter": "python", 379 | "pygments_lexer": "ipython3", 380 | "version": "3.11.7" 381 | } 382 | }, 383 | "nbformat": 4, 384 | "nbformat_minor": 4 385 | } 386 | -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/wp-emoji-release.min.js: -------------------------------------------------------------------------------- 1 | /*! This file is auto-generated */ 2 | // Source: wp-includes/js/twemoji.min.js 3 | var twemoji=function(){"use strict";var f={base:"https://twemoji.maxcdn.com/v/13.0.1/",ext:".png",size:"72x72",className:"emoji",convert:{fromCodePoint:function(d){d="string"==typeof d?parseInt(d,16):d;if(d<65536)return a(d);return a(55296+((d-=65536)>>10),56320+(1023&d))},toCodePoint:i},onerror:function(){this.parentNode&&this.parentNode.replaceChild(g(this.alt,!1),this)},parse:function(d,u){u&&"function"!=typeof u||(u={callback:u});return("string"==typeof d?function(d,b){return o(d,function(d){var u,f,c=d,e=x(d),a=b.callback(e,b);if(e&&a){for(f in c="")}return c})}:function(d,u){var f,c,e,a,b,t,n,r,o,i,s,l=function d(u,f){var c,e,a=u.childNodes,b=a.length;for(;b--;)c=a[b],3===(e=c.nodeType)?f.push(c):1!==e||"ownerSVGElement"in c||h.test(c.nodeName.toLowerCase())||d(c,f);return f}(d,[]),p=l.length;for(;p--;){for(e=!1,a=document.createDocumentFragment(),b=l[p],t=b.nodeValue,n=0;i=m.exec(t);){if((s=i.index)!==n&&a.appendChild(g(t.slice(n,s),!0)),o=i[0],i=x(o),n=s+o.length,s=u.callback(i,u),i&&s){for(c in(r=new Image).onerror=u.onerror,r.setAttribute("draggable","false"),f=u.attributes(o,i))f.hasOwnProperty(c)&&0!==c.indexOf("on")&&!r.hasAttribute(c)&&r.setAttribute(c,f[c]);r.className=u.className,r.alt=o,r.src=s,e=!0,a.appendChild(r)}r||a.appendChild(g(o,!1)),r=null}e&&(n":">","'":"'",'"':"""},m=/(?:\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[\xa9\xae\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udeeb\udeec\udef4-\udefc\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78\udd7a-\uddb4\uddb7\uddba\uddbc-\uddcb\uddd0\uddde-\uddff\ude70-\ude74\ude78-\ude7a\ude80-\ude86\ude90-\udea8\udeb0-\udeb6\udec0-\udec2\uded0-\uded6]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g,c=/\uFE0F/g,e=String.fromCharCode(8205),t=/[&<>'"]/g,h=/^(?:iframe|noframes|noscript|script|select|style|textarea)$/,a=String.fromCharCode;return f;function g(d,u){return document.createTextNode(u?d.replace(c,""):d)}function b(d,u){return"".concat(u.base,u.size,"/",d,u.ext)}function x(d){return i(d.indexOf(e)<0?d.replace(c,""):d)}function n(d){return u[d]}function r(){return null}function o(d,u){return String(d).replace(m,u)}function i(d,u){for(var f=[],c=0,e=0,a=0;aimport.\n", 17 | "\n", 18 | "- Se pueden importar módulos completos, funciones o clases específicas de un módulo, o utilizar un alias para el módulo importado.\n", 19 | "\n", 20 | "Ejemplo:\n", 21 | "\n", 22 | "~~~python\n", 23 | "import math # Importa el módulo math completo\n", 24 | "from math import sqrt # Importa la función sqrt del módulo math\n", 25 | "import numpy as np # Importa el módulo numpy con el alias np\n", 26 | "from scipy import stats # Importa el submódulo stats del paquete scipy\n", 27 | "\n", 28 | "import random\n", 29 | "\n", 30 | "# Generar un número aleatorio entre 0 y 1\n", 31 | "numero_aleatorio = random.random()\n", 32 | "print(\"Número aleatorio:\", numero_aleatorio)\n", 33 | "\n", 34 | "# Generar un número entero aleatorio entre 1 y 10\n", 35 | "numero_entero = random.randint(1, 10)\n", 36 | "print(\"Número entero aleatorio:\", numero_entero)\n", 37 | "\n", 38 | "from math import pi\n", 39 | "\n", 40 | "# Calcular el área de un círculo\n", 41 | "radio = 5\n", 42 | "area_circulo = pi * radio ** 2\n", 43 | "print(\"Área del círculo:\", area_circulo)\n", 44 | "~~~\n", 45 | "\n", 46 | "## B. Creación de módulos y paquetes\n", 47 | "\n", 48 | "- Para crear un módulo en Python, simplemente crea un archivo con la extensión .py y define las funciones, clases y variables que deseas incluir en el módulo.\n", 49 | "\n", 50 | "- Para crear un paquete, crea un directorio con un archivo __init__.py (que puede estar vacío) y coloca los módulos relacionados dentro de ese directorio.\n", 51 | "\n", 52 | "- La estructura de un paquete puede ser similar a la siguiente:\n", 53 | "\n", 54 | "~~~bash\n", 55 | "mi_paquete/\n", 56 | " __init__.py\n", 57 | " modulo1.py\n", 58 | " modulo2.py\n", 59 | " subpaquete/\n", 60 | " __init__.py\n", 61 | " modulo3.py\n", 62 | "~~~\n", 63 | "\n", 64 | "Ejemplo:\n", 65 | "\n", 66 | "Supongamos que queremos crear un paquete llamado estadisticas con dos módulos: >descriptiva.py y inferencial.py.\n", 67 | "\n", 68 | "~~~python\n", 69 | "# estadisticas/descriptiva.py\n", 70 | "def calcular_media(datos):\n", 71 | " return sum(datos) / len(datos)\n", 72 | "\n", 73 | "def calcular_mediana(datos):\n", 74 | " datos_ordenados = sorted(datos)\n", 75 | " n = len(datos_ordenados)\n", 76 | " if n % 2 == 0:\n", 77 | " indice = n // 2\n", 78 | " mediana = (datos_ordenados[indice - 1] + datos_ordenados[indice]) / 2\n", 79 | " else:\n", 80 | " indice = (n - 1) // 2\n", 81 | " mediana = datos_ordenados[indice]\n", 82 | " return mediana\n", 83 | "~~~\n", 84 | "\n", 85 | "~~~python\n", 86 | "# estadisticas/inferencial.py\n", 87 | "from scipy import stats\n", 88 | "\n", 89 | "def prueba_t(muestra1, muestra2):\n", 90 | " t_statistic, p_value = stats.ttest_ind(muestra1, muestra2)\n", 91 | " return t_statistic, p_value\n", 92 | "\n", 93 | "def prueba_anova(muestras):\n", 94 | " f_statistic, p_value = stats.f_oneway(*muestras)\n", 95 | " return f_statistic, p_value\n", 96 | "~~~\n", 97 | "\n", 98 | "Para utilizar los módulos del paquete estadisticas, podemos importarlos de la siguiente manera:\n", 99 | "\n", 100 | "~~~python\n", 101 | "from estadisticas.descriptiva import calcular_media, calcular_mediana\n", 102 | "from estadisticas.inferencial import prueba_t, prueba_anova\n", 103 | "\n", 104 | "datos = [4, 7, 2, 9, 3, 6]\n", 105 | "media = calcular_media(datos)\n", 106 | "mediana = calcular_mediana(datos)\n", 107 | "print(\"Media:\", media)\n", 108 | "print(\"Mediana:\", mediana)\n", 109 | "\n", 110 | "muestra1 = [2, 4, 6, 8, 10]\n", 111 | "muestra2 = [1, 3, 5, 7, 9]\n", 112 | "t_statistic, p_value = prueba_t(muestra1, muestra2)\n", 113 | "print(\"Estadístico t:\", t_statistic)\n", 114 | "print(\"Valor p:\", p_value)\n", 115 | "~~~" 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "id": "e9c1a3d2-1b68-4f2e-a1f8-cdd5c7535004", 121 | "metadata": {}, 122 | "source": [ 123 | "Tomado del material preparado por el profesor [Clifford Torres](https://www.linkedin.com/in/ctorresp27) en el marco del Programa Extensión Universitaria de Ciencia del Dato, que dictamos en conjunto. " 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 69, 129 | "id": "c33f2642-caf0-4683-8b0e-0b2c3b795be1", 130 | "metadata": {}, 131 | "outputs": [], 132 | "source": [ 133 | "class Estudiante:\n", 134 | " def __init__(self, nombre, carrera,\n", 135 | " universidad, anio_egreso):\n", 136 | "\n", 137 | " ## despues del __init__ defino ATRIBUTOS\n", 138 | " self.nombre = nombre\n", 139 | " self.universidad = universidad\n", 140 | " self.carrera = carrera\n", 141 | " self.anio_egreso = anio_egreso\n", 142 | " self.notas = []\n", 143 | " \n", 144 | " ## DEFINO METODOS: \n", 145 | " def agrega_nota(self, nota):\n", 146 | " self.notas.append(nota)\n", 147 | "\n", 148 | " def modifica_nota(self, nota_nueva, i):\n", 149 | " self.notas[i] = nota_nueva\n", 150 | "\n", 151 | " def elimina_nota_mas_baja(self):\n", 152 | " self.notas.remove(min(self.notas))\n", 153 | "\n", 154 | " def correccion_automatica(self):\n", 155 | " self.agrega_nota(5)\n" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 12, 161 | "id": "8f34648b-7faa-4cab-92a2-2e40b331d634", 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "data": { 166 | "text/plain": [ 167 | "type" 168 | ] 169 | }, 170 | "execution_count": 12, 171 | "metadata": {}, 172 | "output_type": "execute_result" 173 | } 174 | ], 175 | "source": [ 176 | "type(Estudiante)" 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": 49, 182 | "id": "feda770b-5202-4e66-9768-6034a59d47fc", 183 | "metadata": {}, 184 | "outputs": [], 185 | "source": [ 186 | "estudiante1 = Estudiante(\"Carla Solis\",\n", 187 | " \"Economía\",\n", 188 | " \"PUCP\", \"2012\")" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": 51, 194 | "id": "a4cc9e64-66f0-4943-ad1b-604aef8ac54d", 195 | "metadata": {}, 196 | "outputs": [ 197 | { 198 | "data": { 199 | "text/plain": [ 200 | "[]" 201 | ] 202 | }, 203 | "execution_count": 51, 204 | "metadata": {}, 205 | "output_type": "execute_result" 206 | } 207 | ], 208 | "source": [ 209 | "estudiante1.notas" 210 | ] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "execution_count": 53, 215 | "id": "7a1e424e-1dc7-4ecb-850d-9ad486bc8aef", 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "estudiante1.agrega_nota(10)" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": 55, 225 | "id": "1adc6897-5d65-4229-8bb1-6e05c7e1e5d8", 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "estudiante1.agrega_nota(14)" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": 57, 235 | "id": "42366e06-3790-4f33-82ac-f52f1cbd4ca9", 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "estudiante1.agrega_nota(14.5)" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": 59, 245 | "id": "b719bf25-9847-42c9-86aa-1e861feb0c27", 246 | "metadata": {}, 247 | "outputs": [], 248 | "source": [ 249 | "estudiante1.agrega_nota(15)" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 63, 255 | "id": "a716f095-7840-4180-838f-1e0f7b8b27cb", 256 | "metadata": {}, 257 | "outputs": [], 258 | "source": [ 259 | "estudiante1.elimina_nota_mas_baja()" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": 67, 265 | "id": "109f54e2-3316-4d39-aa33-f3cf546f4d28", 266 | "metadata": {}, 267 | "outputs": [ 268 | { 269 | "data": { 270 | "text/plain": [ 271 | "[14, 14.5, 15]" 272 | ] 273 | }, 274 | "execution_count": 67, 275 | "metadata": {}, 276 | "output_type": "execute_result" 277 | } 278 | ], 279 | "source": [ 280 | "estudiante1.notas" 281 | ] 282 | }, 283 | { 284 | "cell_type": "code", 285 | "execution_count": 71, 286 | "id": "6d88487e-a2c2-4843-9b41-d46eb4a39340", 287 | "metadata": {}, 288 | "outputs": [ 289 | { 290 | "data": { 291 | "text/plain": [ 292 | "'Carla Solis'" 293 | ] 294 | }, 295 | "execution_count": 71, 296 | "metadata": {}, 297 | "output_type": "execute_result" 298 | } 299 | ], 300 | "source": [ 301 | "estudiante1.nombre" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 73, 307 | "id": "af40e48b-a70c-4842-9cf6-3deba5799f60", 308 | "metadata": {}, 309 | "outputs": [], 310 | "source": [ 311 | "estudiante1.agrega_nota(20)" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": 77, 317 | "id": "6a7836db-b5d4-4fdc-b22c-df0e9cec3069", 318 | "metadata": {}, 319 | "outputs": [ 320 | { 321 | "data": { 322 | "text/plain": [ 323 | "[14, 14.5, 15, 20]" 324 | ] 325 | }, 326 | "execution_count": 77, 327 | "metadata": {}, 328 | "output_type": "execute_result" 329 | } 330 | ], 331 | "source": [ 332 | "estudiante1.notas" 333 | ] 334 | }, 335 | { 336 | "cell_type": "code", 337 | "execution_count": 83, 338 | "id": "2a07ab01-9a04-4b49-ba4d-736a95544c38", 339 | "metadata": {}, 340 | "outputs": [], 341 | "source": [ 342 | "lista_personas = []\n", 343 | "for year in range(2010, 2030): \n", 344 | " lista_personas.append([\"Carla Solis\",\"Economía\",\"PUCP\", f\"{year}\"]),\n" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": 105, 350 | "id": "8f81867b-58a0-4bda-9ba4-4a5bf5940e7d", 351 | "metadata": {}, 352 | "outputs": [ 353 | { 354 | "data": { 355 | "text/plain": [ 356 | "[['Carla Solis', 'Economía', 'PUCP', '2010'],\n", 357 | " ['Carla Solis', 'Economía', 'PUCP', '2011'],\n", 358 | " ['Carla Solis', 'Economía', 'PUCP', '2012'],\n", 359 | " ['Carla Solis', 'Economía', 'PUCP', '2013'],\n", 360 | " ['Carla Solis', 'Economía', 'PUCP', '2014'],\n", 361 | " ['Carla Solis', 'Economía', 'PUCP', '2015'],\n", 362 | " ['Carla Solis', 'Economía', 'PUCP', '2016'],\n", 363 | " ['Carla Solis', 'Economía', 'PUCP', '2017'],\n", 364 | " ['Carla Solis', 'Economía', 'PUCP', '2018'],\n", 365 | " ['Carla Solis', 'Economía', 'PUCP', '2019'],\n", 366 | " ['Carla Solis', 'Economía', 'PUCP', '2020'],\n", 367 | " ['Carla Solis', 'Economía', 'PUCP', '2021'],\n", 368 | " ['Carla Solis', 'Economía', 'PUCP', '2022'],\n", 369 | " ['Carla Solis', 'Economía', 'PUCP', '2023'],\n", 370 | " ['Carla Solis', 'Economía', 'PUCP', '2024'],\n", 371 | " ['Carla Solis', 'Economía', 'PUCP', '2025'],\n", 372 | " ['Carla Solis', 'Economía', 'PUCP', '2026'],\n", 373 | " ['Carla Solis', 'Economía', 'PUCP', '2027'],\n", 374 | " ['Carla Solis', 'Economía', 'PUCP', '2028'],\n", 375 | " ['Carla Solis', 'Economía', 'PUCP', '2029']]" 376 | ] 377 | }, 378 | "execution_count": 105, 379 | "metadata": {}, 380 | "output_type": "execute_result" 381 | } 382 | ], 383 | "source": [ 384 | "lista_personas" 385 | ] 386 | }, 387 | { 388 | "cell_type": "code", 389 | "execution_count": 91, 390 | "id": "880d1582-912d-400a-9a1f-cf68510e34b6", 391 | "metadata": {}, 392 | "outputs": [], 393 | "source": [ 394 | "estudiantes_objeto = {}\n", 395 | "for i, persona in enumerate(lista_personas):\n", 396 | " estudiantes_objeto[i] = Estudiante(persona[0], persona[1],\n", 397 | " persona[2], persona[3])\n", 398 | " " 399 | ] 400 | } 401 | ], 402 | "metadata": { 403 | "kernelspec": { 404 | "display_name": "Python [conda env:anaconda3-2]", 405 | "language": "python", 406 | "name": "conda-env-anaconda3-2-py" 407 | }, 408 | "language_info": { 409 | "codemirror_mode": { 410 | "name": "ipython", 411 | "version": 3 412 | }, 413 | "file_extension": ".py", 414 | "mimetype": "text/x-python", 415 | "name": "python", 416 | "nbconvert_exporter": "python", 417 | "pygments_lexer": "ipython3", 418 | "version": "3.8.8" 419 | } 420 | }, 421 | "nbformat": 4, 422 | "nbformat_minor": 5 423 | } 424 | -------------------------------------------------------------------------------- /Clase 5/data/world-happiness-report-2023-countries.csv: -------------------------------------------------------------------------------- 1 | Country name,Ladder score,Standard error of ladder score,upperwhisker,lowerwhisker,Logged GDP per capita,Social support,Healthy life expectancy,Freedom to make life choices,Generosity,Perceptions of corruption,Ladder score in Dystopia,Explained by: Log GDP per capita,Explained by: Social support,Explained by: Healthy life expectancy,Explained by: Freedom to make life choices,Explained by: Generosity,Explained by: Perceptions of corruption,Dystopia + residual 2 | Finland,7.804,0.036,7.875,7.733,10.792,0.969,71.150,0.961,-0.019,0.182,1.778,1.888,1.585,0.535,0.772,0.126,0.535,2.363 3 | Denmark,7.586,0.041,7.667,7.506,10.962,0.954,71.250,0.934,0.134,0.196,1.778,1.949,1.548,0.537,0.734,0.208,0.525,2.084 4 | Iceland,7.530,0.049,7.625,7.434,10.896,0.983,72.050,0.936,0.211,0.668,1.778,1.926,1.620,0.559,0.738,0.250,0.187,2.250 5 | Israel,7.473,0.032,7.535,7.411,10.639,0.943,72.697,0.809,-0.023,0.708,1.778,1.833,1.521,0.577,0.569,0.124,0.158,2.691 6 | Netherlands,7.403,0.029,7.460,7.346,10.942,0.930,71.550,0.887,0.213,0.379,1.778,1.942,1.488,0.545,0.672,0.251,0.394,2.110 7 | Sweden,7.395,0.037,7.468,7.322,10.883,0.939,72.150,0.948,0.165,0.202,1.778,1.921,1.510,0.562,0.754,0.225,0.520,1.903 8 | Norway,7.315,0.044,7.402,7.229,11.088,0.943,71.500,0.947,0.141,0.283,1.778,1.994,1.521,0.544,0.752,0.212,0.463,1.829 9 | Switzerland,7.240,0.043,7.324,7.156,11.164,0.920,72.900,0.891,0.027,0.266,1.778,2.022,1.463,0.582,0.678,0.151,0.475,1.870 10 | Luxembourg,7.228,0.069,7.363,7.093,11.660,0.879,71.675,0.915,0.024,0.345,1.778,2.200,1.357,0.549,0.710,0.149,0.418,1.845 11 | New Zealand,7.123,0.038,7.198,7.048,10.662,0.952,70.350,0.887,0.175,0.271,1.778,1.842,1.544,0.513,0.672,0.230,0.471,1.852 12 | Austria,7.097,0.040,7.176,7.018,10.899,0.888,71.150,0.855,0.102,0.497,1.778,1.927,1.382,0.535,0.630,0.191,0.310,2.124 13 | Australia,7.095,0.044,7.180,7.009,10.821,0.934,71.050,0.890,0.198,0.496,1.778,1.899,1.497,0.532,0.677,0.242,0.310,1.938 14 | Canada,6.961,0.042,7.042,6.879,10.773,0.929,71.400,0.874,0.153,0.420,1.778,1.881,1.484,0.541,0.656,0.218,0.364,1.815 15 | Ireland,6.911,0.044,6.996,6.825,11.527,0.905,71.300,0.874,0.092,0.358,1.778,2.152,1.425,0.539,0.656,0.186,0.409,1.545 16 | United States,6.894,0.047,6.986,6.802,11.048,0.919,65.850,0.800,0.137,0.689,1.778,1.980,1.460,0.390,0.557,0.210,0.172,2.124 17 | Germany,6.892,0.049,6.989,6.795,10.879,0.896,71.300,0.846,0.030,0.420,1.778,1.919,1.401,0.539,0.618,0.153,0.365,1.898 18 | Belgium,6.859,0.034,6.926,6.793,10.844,0.915,70.899,0.825,0.001,0.549,1.778,1.907,1.449,0.528,0.590,0.137,0.273,1.976 19 | Czechia,6.845,0.044,6.931,6.759,10.611,0.953,69.050,0.903,0.040,0.859,1.778,1.823,1.544,0.477,0.693,0.158,0.050,2.099 20 | United Kingdom,6.796,0.042,6.877,6.714,10.704,0.882,70.300,0.852,0.253,0.454,1.778,1.857,1.366,0.511,0.626,0.272,0.340,1.822 21 | Lithuania,6.763,0.044,6.849,6.677,10.568,0.939,67.397,0.748,-0.145,0.805,1.778,1.808,1.511,0.432,0.487,0.059,0.089,2.377 22 | France,6.661,0.038,6.735,6.588,10.701,0.909,72.300,0.819,-0.100,0.553,1.778,1.856,1.433,0.566,0.582,0.083,0.270,1.872 23 | Slovenia,6.650,0.051,6.750,6.550,10.588,0.951,71.052,0.913,0.014,0.771,1.778,1.815,1.539,0.532,0.707,0.144,0.113,1.799 24 | Costa Rica,6.609,0.052,6.710,6.507,9.952,0.872,70.000,0.895,-0.070,0.768,1.778,1.587,1.340,0.503,0.683,0.099,0.116,2.281 25 | Romania,6.589,0.052,6.690,6.488,10.339,0.848,67.051,0.856,-0.172,0.929,1.778,1.726,1.280,0.423,0.631,0.044,0.000,2.485 26 | Singapore,6.587,0.068,6.720,6.454,11.571,0.878,73.800,0.878,0.063,0.146,1.778,2.168,1.354,0.607,0.660,0.170,0.561,1.067 27 | United Arab Emirates,6.571,0.043,6.656,6.486,11.145,0.826,66.243,0.942,0.096,0.584,1.778,2.015,1.223,0.401,0.745,0.188,0.247,1.752 28 | Taiwan Province of China,6.535,0.047,6.627,6.444,10.797,0.884,69.600,0.804,-0.129,0.681,1.778,1.890,1.372,0.492,0.562,0.067,0.178,1.974 29 | Uruguay,6.494,0.046,6.583,6.404,10.037,0.913,67.500,0.895,-0.065,0.575,1.778,1.617,1.445,0.435,0.683,0.102,0.254,1.958 30 | Slovakia,6.469,0.056,6.578,6.360,10.353,0.953,68.838,0.753,-0.016,0.898,1.778,1.731,1.544,0.472,0.494,0.128,0.022,2.078 31 | Saudi Arabia,6.463,0.061,6.581,6.344,10.715,0.884,64.399,0.894,-0.081,0.691,1.778,1.861,1.370,0.351,0.682,0.093,0.170,1.936 32 | Estonia,6.455,0.040,6.534,6.377,10.541,0.946,69.650,0.929,0.032,0.409,1.778,1.798,1.526,0.494,0.728,0.153,0.372,1.383 33 | Spain,6.436,0.042,6.519,6.354,10.540,0.932,72.350,0.782,-0.066,0.711,1.778,1.798,1.491,0.567,0.533,0.101,0.157,1.789 34 | Italy,6.405,0.054,6.511,6.298,10.634,0.882,72.050,0.711,-0.074,0.842,1.778,1.832,1.365,0.559,0.438,0.097,0.063,2.052 35 | Kosovo,6.368,0.060,6.485,6.250,9.359,0.844,65.195,0.861,0.259,0.866,1.778,1.374,1.269,0.372,0.639,0.275,0.045,2.393 36 | Chile,6.334,0.046,6.424,6.243,10.114,0.889,70.300,0.792,-0.011,0.823,1.778,1.645,1.384,0.511,0.546,0.131,0.076,2.040 37 | Mexico,6.330,0.057,6.441,6.218,9.850,0.804,65.800,0.856,-0.094,0.768,1.778,1.550,1.169,0.389,0.632,0.086,0.115,2.389 38 | Malta,6.300,0.045,6.388,6.212,10.661,0.923,71.600,0.886,0.119,0.729,1.778,1.841,1.468,0.547,0.671,0.200,0.143,1.429 39 | Panama,6.265,0.081,6.424,6.105,10.305,0.896,68.950,0.855,-0.133,0.878,1.778,1.714,1.402,0.475,0.630,0.065,0.036,1.943 40 | Poland,6.260,0.042,6.343,6.177,10.453,0.925,69.049,0.765,-0.031,0.736,1.778,1.767,1.474,0.477,0.511,0.120,0.139,1.772 41 | Nicaragua,6.259,0.076,6.408,6.109,8.618,0.853,65.650,0.877,0.021,0.625,1.778,1.109,1.292,0.385,0.660,0.148,0.218,2.448 42 | Latvia,6.213,0.042,6.295,6.131,10.370,0.937,66.400,0.818,-0.056,0.830,1.778,1.737,1.505,0.405,0.580,0.107,0.071,1.808 43 | Bahrain,6.173,0.100,6.369,5.977,10.776,0.844,65.825,0.944,0.117,0.737,1.778,1.883,1.269,0.389,0.748,0.199,0.138,1.546 44 | Guatemala,6.150,0.108,6.362,5.939,9.116,0.812,62.900,0.856,-0.057,0.837,1.778,1.287,1.188,0.310,0.631,0.106,0.066,2.562 45 | Kazakhstan,6.144,0.048,6.239,6.049,10.166,0.931,65.802,0.853,0.000,0.721,1.778,1.664,1.491,0.389,0.628,0.136,0.149,1.688 46 | Serbia,6.144,0.079,6.299,5.988,9.854,0.873,67.088,0.845,0.204,0.816,1.778,1.552,1.343,0.424,0.617,0.246,0.081,1.881 47 | Cyprus,6.130,0.054,6.236,6.024,10.611,0.826,72.802,0.724,-0.060,0.860,1.778,1.824,1.224,0.580,0.455,0.104,0.050,1.893 48 | Japan,6.129,0.042,6.211,6.047,10.616,0.894,74.349,0.799,-0.237,0.640,1.778,1.825,1.396,0.622,0.556,0.009,0.207,1.513 49 | Croatia,6.125,0.057,6.237,6.013,10.341,0.917,68.950,0.757,-0.093,0.925,1.778,1.727,1.455,0.475,0.500,0.087,0.003,1.880 50 | Brazil,6.125,0.065,6.252,5.997,9.582,0.836,65.749,0.801,-0.009,0.738,1.778,1.454,1.250,0.387,0.558,0.131,0.137,2.205 51 | El Salvador,6.122,0.069,6.257,5.986,9.089,0.755,65.597,0.918,-0.108,0.620,1.778,1.278,1.044,0.383,0.713,0.079,0.222,2.403 52 | Hungary,6.041,0.055,6.149,5.933,10.419,0.943,67.500,0.758,-0.059,0.839,1.778,1.754,1.519,0.435,0.501,0.105,0.065,1.663 53 | Argentina,6.024,0.063,6.147,5.900,9.959,0.891,67.200,0.823,-0.089,0.814,1.778,1.590,1.388,0.427,0.587,0.088,0.082,1.861 54 | Honduras,6.023,0.089,6.196,5.849,8.635,0.766,64.063,0.843,0.097,0.843,1.778,1.115,1.072,0.341,0.613,0.189,0.062,2.631 55 | Uzbekistan,6.014,0.059,6.130,5.899,8.948,0.875,65.301,0.938,0.230,0.638,1.778,1.227,1.347,0.375,0.740,0.260,0.208,1.856 56 | Malaysia,6.012,0.079,6.167,5.858,10.169,0.799,65.662,0.877,0.160,0.758,1.778,1.665,1.155,0.385,0.659,0.222,0.122,1.804 57 | Portugal,5.968,0.055,6.076,5.860,10.429,0.878,71.250,0.902,-0.196,0.878,1.778,1.758,1.356,0.537,0.693,0.031,0.037,1.556 58 | South Korea,5.951,0.045,6.040,5.862,10.693,0.812,73.650,0.717,-0.046,0.701,1.778,1.853,1.188,0.603,0.446,0.112,0.163,1.587 59 | Greece,5.931,0.048,6.024,5.838,10.288,0.835,71.150,0.568,-0.240,0.793,1.778,1.708,1.247,0.535,0.248,0.008,0.097,2.089 60 | Mauritius,5.902,0.057,6.013,5.791,9.957,0.888,63.850,0.813,-0.028,0.775,1.778,1.589,1.382,0.336,0.574,0.121,0.110,1.790 61 | Thailand,5.843,0.064,5.969,5.717,9.751,0.874,68.450,0.850,0.289,0.910,1.778,1.515,1.344,0.461,0.624,0.291,0.013,1.594 62 | Mongolia,5.840,0.046,5.930,5.750,9.372,0.933,60.500,0.701,0.190,0.849,1.778,1.379,1.494,0.244,0.425,0.239,0.058,2.001 63 | Kyrgyzstan,5.825,0.045,5.913,5.737,8.486,0.911,66.852,0.934,0.181,0.904,1.778,1.061,1.439,0.417,0.735,0.234,0.018,1.920 64 | Moldova,5.819,0.052,5.922,5.717,9.499,0.857,65.299,0.840,-0.080,0.901,1.778,1.425,1.302,0.375,0.610,0.093,0.020,1.995 65 | China,5.818,0.044,5.905,5.731,9.738,0.836,68.689,0.882,-0.041,0.727,1.778,1.510,1.249,0.468,0.666,0.115,0.145,1.666 66 | Vietnam,5.763,0.052,5.865,5.662,9.287,0.821,65.502,0.939,-0.004,0.759,1.778,1.349,1.212,0.381,0.741,0.134,0.122,1.824 67 | Paraguay,5.738,0.058,5.851,5.625,9.510,0.906,65.900,0.891,0.021,0.843,1.778,1.428,1.427,0.392,0.678,0.148,0.062,1.604 68 | Montenegro,5.722,0.112,5.941,5.503,9.813,0.890,67.100,0.805,0.063,0.844,1.778,1.537,1.385,0.424,0.563,0.170,0.061,1.581 69 | Jamaica,5.703,0.089,5.876,5.529,9.165,0.867,66.600,0.822,-0.106,0.875,1.778,1.305,1.329,0.411,0.587,0.079,0.039,1.954 70 | Bolivia,5.684,0.057,5.797,5.572,8.985,0.811,63.599,0.868,-0.063,0.846,1.778,1.240,1.187,0.329,0.648,0.103,0.060,2.118 71 | Russia,5.661,0.037,5.734,5.588,10.210,0.889,64.947,0.719,-0.030,0.801,1.778,1.680,1.383,0.366,0.449,0.120,0.091,1.572 72 | Bosnia and Herzegovina,5.633,0.073,5.775,5.490,9.616,0.880,67.275,0.746,0.206,0.918,1.778,1.467,1.361,0.429,0.485,0.247,0.008,1.635 73 | Colombia,5.630,0.060,5.747,5.514,9.584,0.822,69.350,0.804,-0.104,0.834,1.778,1.455,1.213,0.486,0.562,0.080,0.068,1.765 74 | Dominican Republic,5.569,0.073,5.712,5.426,9.811,0.827,64.399,0.850,-0.099,0.657,1.778,1.536,1.227,0.351,0.623,0.083,0.195,1.553 75 | Ecuador,5.559,0.063,5.682,5.436,9.270,0.806,69.000,0.802,-0.108,0.833,1.778,1.343,1.173,0.476,0.560,0.079,0.069,1.860 76 | Peru,5.526,0.058,5.640,5.412,9.402,0.798,69.850,0.794,-0.119,0.892,1.778,1.390,1.153,0.499,0.549,0.073,0.027,1.835 77 | Philippines,5.523,0.077,5.675,5.371,8.979,0.780,62.038,0.919,-0.060,0.732,1.778,1.238,1.108,0.286,0.714,0.104,0.141,1.931 78 | Bulgaria,5.466,0.059,5.582,5.350,10.087,0.918,66.500,0.801,-0.057,0.911,1.778,1.635,1.457,0.408,0.557,0.106,0.013,1.289 79 | Nepal,5.360,0.075,5.507,5.214,8.256,0.748,61.847,0.808,0.146,0.783,1.778,0.979,1.027,0.281,0.567,0.215,0.104,2.187 80 | Armenia,5.342,0.066,5.470,5.213,9.615,0.790,67.789,0.796,-0.155,0.705,1.778,1.466,1.134,0.443,0.551,0.053,0.160,1.534 81 | Tajikistan,5.330,0.062,5.452,5.207,8.237,0.836,62.226,0.832,-0.060,0.522,1.778,0.972,1.248,0.291,0.599,0.104,0.292,1.823 82 | Algeria,5.329,0.062,5.451,5.207,9.300,0.855,66.549,0.571,-0.117,0.717,1.778,1.353,1.298,0.409,0.252,0.073,0.152,1.791 83 | Hong Kong S.A.R. of China,5.308,0.048,5.403,5.214,10.966,0.817,77.280,0.687,-0.026,0.385,1.778,1.951,1.201,0.702,0.407,0.123,0.390,0.535 84 | Albania,5.277,0.066,5.406,5.148,9.567,0.718,69.150,0.794,-0.007,0.878,1.778,1.449,0.951,0.480,0.549,0.133,0.037,1.678 85 | Indonesia,5.277,0.059,5.392,5.161,9.385,0.804,63.048,0.880,0.531,0.876,1.778,1.384,1.169,0.314,0.663,0.422,0.038,1.288 86 | South Africa,5.275,0.073,5.417,5.132,9.478,0.907,56.989,0.730,-0.087,0.902,1.778,1.417,1.428,0.149,0.464,0.090,0.019,1.708 87 | Congo (Brazzaville),5.267,0.088,5.440,5.094,8.095,0.605,56.850,0.730,-0.004,0.739,1.778,0.921,0.665,0.145,0.464,0.134,0.136,2.802 88 | North Macedonia,5.254,0.055,5.361,5.146,9.703,0.805,66.500,0.769,0.131,0.902,1.778,1.498,1.171,0.408,0.515,0.207,0.020,1.435 89 | Venezuela,5.211,0.064,5.336,5.085,5.527,0.839,64.050,0.659,0.128,0.811,1.778,0.000,1.257,0.341,0.369,0.205,0.084,2.955 90 | Laos,5.111,0.081,5.269,4.952,8.962,0.679,60.946,0.919,0.091,0.703,1.778,1.232,0.853,0.257,0.715,0.185,0.162,1.707 91 | Georgia,5.109,0.056,5.219,5.000,9.646,0.716,64.950,0.786,-0.254,0.649,1.778,1.477,0.947,0.366,0.539,0.000,0.201,1.580 92 | Guinea,5.072,0.072,5.213,4.931,7.880,0.649,54.185,0.659,0.125,0.787,1.778,0.844,0.776,0.072,0.369,0.204,0.102,2.705 93 | Ukraine,5.071,0.059,5.187,4.956,9.314,0.878,64.550,0.795,0.240,0.907,1.778,1.358,1.354,0.355,0.551,0.265,0.016,1.172 94 | Ivory Coast,5.053,0.074,5.198,4.907,8.576,0.572,55.953,0.733,0.003,0.746,1.778,1.094,0.584,0.120,0.467,0.138,0.131,2.519 95 | Gabon,5.035,0.072,5.175,4.894,9.537,0.746,58.252,0.642,-0.187,0.786,1.778,1.438,1.021,0.183,0.346,0.036,0.102,1.908 96 | Nigeria,4.981,0.080,5.136,4.825,8.496,0.740,54.891,0.718,0.073,0.911,1.778,1.065,1.007,0.092,0.448,0.176,0.013,2.181 97 | Cameroon,4.973,0.071,5.112,4.834,8.217,0.686,55.847,0.686,0.015,0.846,1.778,0.965,0.871,0.118,0.405,0.144,0.059,2.411 98 | Mozambique,4.954,0.116,5.181,4.727,7.116,0.692,51.530,0.851,0.047,0.660,1.778,0.570,0.885,0.000,0.625,0.161,0.192,2.519 99 | Iraq,4.941,0.081,5.099,4.783,9.098,0.718,63.415,0.646,-0.005,0.876,1.778,1.281,0.953,0.324,0.351,0.134,0.038,1.861 100 | State of Palestine,4.908,0.092,5.089,4.727,8.716,0.859,,0.694,-0.132,0.836,1.778,1.144,1.309,,0.416,0.065,0.067, 101 | Morocco,4.903,0.061,5.023,4.783,8.973,0.553,63.901,0.787,-0.231,0.811,1.778,1.236,0.535,0.337,0.540,0.013,0.085,2.158 102 | Iran,4.876,0.053,4.980,4.772,9.610,0.778,66.600,0.593,0.173,0.747,1.778,1.465,1.102,0.411,0.281,0.229,0.130,1.259 103 | Senegal,4.855,0.065,4.983,4.727,8.155,0.629,59.999,0.772,0.011,0.846,1.778,0.943,0.727,0.231,0.519,0.142,0.060,2.234 104 | Mauritania,4.724,0.147,5.011,4.437,8.591,0.644,60.475,0.622,-0.013,0.657,1.778,1.099,0.764,0.244,0.320,0.130,0.195,1.973 105 | Burkina Faso,4.638,0.093,4.819,4.456,7.667,0.663,55.461,0.696,0.095,0.771,1.778,0.768,0.814,0.107,0.419,0.188,0.113,2.230 106 | Namibia,4.631,0.069,4.766,4.496,9.121,0.787,56.851,0.669,-0.126,0.830,1.778,1.289,1.126,0.145,0.383,0.069,0.071,1.549 107 | Turkiye,4.614,0.083,4.777,4.450,10.307,0.796,68.663,0.475,-0.077,0.795,1.778,1.714,1.148,0.467,0.125,0.095,0.096,0.969 108 | Ghana,4.605,0.063,4.729,4.481,8.596,0.641,58.763,0.777,0.139,0.881,1.778,1.101,0.756,0.197,0.526,0.211,0.035,1.779 109 | Pakistan,4.555,0.077,4.707,4.404,8.540,0.601,57.313,0.766,0.008,0.787,1.778,1.081,0.657,0.158,0.511,0.141,0.102,1.907 110 | Niger,4.501,0.108,4.712,4.291,7.091,0.590,56.550,0.788,0.032,0.734,1.778,0.561,0.628,0.137,0.540,0.154,0.140,2.341 111 | Tunisia,4.497,0.053,4.601,4.393,9.244,0.730,67.000,0.576,-0.213,0.907,1.778,1.333,0.981,0.422,0.259,0.022,0.016,1.463 112 | Kenya,4.487,0.066,4.616,4.357,8.458,0.690,58.499,0.696,0.288,0.852,1.778,1.051,0.881,0.190,0.418,0.291,0.055,1.601 113 | Sri Lanka,4.442,0.083,4.603,4.280,9.491,0.826,67.150,0.787,-0.030,0.808,1.778,1.422,1.224,0.426,0.539,0.120,0.086,0.625 114 | Uganda,4.432,0.089,4.607,4.258,7.716,0.794,58.913,0.701,0.114,0.857,1.778,0.785,1.144,0.201,0.425,0.197,0.051,1.628 115 | Chad,4.397,0.121,4.633,4.160,7.261,0.722,53.125,0.677,0.221,0.807,1.778,0.622,0.962,0.043,0.393,0.255,0.088,2.034 116 | Cambodia,4.393,0.059,4.508,4.279,8.385,0.747,61.900,0.958,0.073,0.857,1.778,1.025,1.024,0.283,0.768,0.176,0.051,1.068 117 | Benin,4.374,0.066,4.504,4.244,8.103,0.437,56.095,0.743,-0.043,0.576,1.778,0.924,0.242,0.124,0.481,0.114,0.253,2.235 118 | Myanmar,4.372,0.082,4.533,4.212,8.404,0.787,61.388,0.727,0.491,0.658,1.778,1.032,1.125,0.269,0.460,0.400,0.194,0.893 119 | Bangladesh,4.282,0.068,4.416,4.148,8.685,0.544,64.548,0.845,0.005,0.698,1.778,1.133,0.513,0.355,0.617,0.139,0.165,1.361 120 | Gambia,4.279,0.105,4.484,4.075,7.648,0.584,57.900,0.596,0.364,0.883,1.778,0.761,0.614,0.174,0.286,0.332,0.033,2.081 121 | Mali,4.198,0.062,4.319,4.076,7.655,0.593,55.403,0.713,-0.028,0.846,1.778,0.763,0.637,0.106,0.441,0.121,0.059,2.070 122 | Egypt,4.170,0.059,4.287,4.054,9.367,0.726,63.503,0.732,-0.183,0.580,1.778,1.377,0.972,0.326,0.467,0.038,0.250,0.740 123 | Togo,4.137,0.077,4.289,3.986,7.673,0.595,57.449,0.657,0.024,0.740,1.778,0.770,0.642,0.161,0.367,0.149,0.136,1.913 124 | Jordan,4.120,0.062,4.242,3.997,9.130,0.729,67.600,0.770,-0.150,0.687,1.778,1.292,0.980,0.438,0.517,0.056,0.173,0.663 125 | Ethiopia,4.091,0.093,4.273,3.908,7.739,0.782,60.698,0.720,0.273,0.789,1.778,0.793,1.114,0.250,0.451,0.283,0.101,1.099 126 | Liberia,4.042,0.144,4.325,3.760,7.277,0.596,56.700,0.735,0.154,0.830,1.778,0.628,0.644,0.141,0.471,0.219,0.071,1.869 127 | India,4.036,0.029,4.092,3.980,8.759,0.608,60.777,0.897,0.072,0.774,1.778,1.159,0.674,0.252,0.685,0.175,0.111,0.979 128 | Madagascar,4.019,0.092,4.199,3.839,7.290,0.650,58.050,0.522,0.075,0.742,1.778,0.632,0.779,0.178,0.187,0.177,0.134,1.932 129 | Zambia,3.982,0.094,4.167,3.797,8.074,0.694,55.032,0.791,0.098,0.818,1.778,0.914,0.890,0.095,0.545,0.189,0.080,1.270 130 | Tanzania,3.694,0.075,3.840,3.547,7.857,0.653,59.401,0.838,0.182,0.554,1.778,0.836,0.787,0.214,0.607,0.234,0.269,0.747 131 | Comoros,3.545,0.117,3.774,3.317,8.075,0.471,59.425,0.470,-0.014,0.727,1.778,0.914,0.327,0.215,0.117,0.129,0.145,1.699 132 | Malawi,3.495,0.090,3.671,3.320,7.302,0.531,58.475,0.750,0.005,0.749,1.778,0.637,0.479,0.189,0.490,0.139,0.129,1.432 133 | Botswana,3.435,0.136,3.702,3.168,9.629,0.753,54.725,0.742,-0.215,0.830,1.778,1.471,1.041,0.087,0.480,0.021,0.071,0.264 134 | Congo (Kinshasa),3.207,0.095,3.394,3.020,7.007,0.652,55.375,0.664,0.086,0.834,1.778,0.531,0.784,0.105,0.375,0.183,0.068,1.162 135 | Zimbabwe,3.204,0.061,3.323,3.084,7.641,0.690,54.050,0.654,-0.046,0.766,1.778,0.758,0.881,0.069,0.363,0.112,0.117,0.905 136 | Sierra Leone,3.138,0.082,3.299,2.976,7.394,0.555,54.900,0.660,0.105,0.858,1.778,0.670,0.540,0.092,0.371,0.193,0.051,1.221 137 | Lebanon,2.392,0.044,2.479,2.305,9.478,0.530,66.149,0.474,-0.141,0.891,1.778,1.417,0.476,0.398,0.123,0.061,0.027,-0.110 138 | Afghanistan,1.859,0.033,1.923,1.795,7.324,0.341,54.712,0.382,-0.081,0.847,1.778,0.645,0.000,0.087,0.000,0.093,0.059,0.976 -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/current.js: -------------------------------------------------------------------------------- 1 | window._hsq=window._hsq||[];window.hbspt=window.hbspt||{};window.hbspt.cta=window.hbspt.cta||{__hstc:"",__hssc:"",__hsfp:"",__utk:"",__generated_utk:"",email:"",__analyticsPageId:"",__path:"",__referrerPath:"",TRACKING_CODE_TIMEOUT:2e3,WEB_INTERACTIVE_POLLING_INTERVAL:200,placementsData:{},placementsLoadQueue:{},loadedQueue:!1,canonicalURL:"",queryStringToForward:["tc_country","tc_deviceCategory","tc_visitSource","tc_drillDownRule","tc_language","utm_campaign","utm_medium"],trackingKeys:{RENDER_SUCCESS:"cta-render-success",RENDER_TIMEOUT:"cta-render-timeout",CTA_JSON_SUCCESS:"cta-json-success",CTA_JSON_FAILURE:"cta-json-failure",WITH_ANALYTICS:"cta-with-analytics"},load:function(t,e,a){var i=this,n=!1;i.utils.log(e+" loading");a||(a={region:"na1"});a.region||(a.region="na1");a.useNewLoader=!0;i.utils.setTrackingEnv(a.env,a.region,t);i.placementsData[e]=i.placementsData[e]||{portalId:t,loadCallTimestamp:(new Date).getTime()};i.utils.changeCtaVisibility(e,"hidden");i.__utk=i.__utk||i.utils.getCookieValue("hubspotutk");i.__hssc=i.__hssc||i.utils.getCookieValue("__hssc");i.__hstc=i.__hstc||i.utils.getCookieValue("__hstc");a.enforceTargetIsBlank&&(i.enforceTargetIsBlank=!0);i.canonicalURL=i.canonicalURL||i.getCanonicalURL();i.utils.isPreviewUrl&&(i.email=i.utils.getParameterByName("email"));i.setPlacementData(e,a,"t");function s(s){if(!n){i.__utk||(i.__generated_utk=i.utils.generateUtk());i.displayCta(t,e,a,s);n=!0}}function r(t){window._hsq.push((function(e){i.utils.track(i.trackingKeys.WITH_ANALYTICS);i.__path=e.path;i.__referrerPath=e.referrerPath;i.__analyticsPageId=window.hsVars&&window.hsVars.analytics_page_id||e.pageId;i.__hsfp=e._getFingerprint();if(e.utk){i.__hstc=e.utk.get();i.__utk=e.utk.visitor}e.session&&(i.__hssc=e.session.get());e.contentType&&(i.__contentType=e.contentType);t()}))}if(a.useNewLoader){i.addToQueue(t,e,a);i.utils.isPreviewUrl||r((function(){i.utils.log("got tracker data")}));i.utils.domReady((function(){if(!i.loadedQueue){i.setupCMSAnalytics();i.loadedQueue=!0;setTimeout((function(){i.loadQueue()}))}}));window.setTimeout((function(){if(!i.placementsData[e].ctaLoaded){i.utils.log(e+" timed out");i.utils.track(i.trackingKeys.RENDER_TIMEOUT);i.utils.changeCtaVisibility(e,"visible")}}),i.TRACKING_CODE_TIMEOUT)}else if(i.utils.isPreviewUrl)s();else{r((function(){i.utils.log(e+" get tracker data");s("a")}));i.utils.domReady((function(){i.setupCMSAnalytics();var t=!!i.__analyticsPageId||!i.__isCos,e=!!i.__utk,a=!!i.__path||!i.shouldWaitForPath();e&&t&&a&&s("d")}));window.setTimeout((function(){if(!n){i.utils.track(i.trackingKeys.RENDER_TIMEOUT);i.utils.log(e+" timed out");s("t")}}),i.TRACKING_CODE_TIMEOUT)}},shouldWaitForPath:function(){for(var t=0;t-1&&!e.getAttribute("data-hs-drop")}}for(i=0;i{clearTimeout(self.webInteractiveClientTimeout);window.__PRIVATE__HubspotCtaClient?t():self.pollForWebInteractiveClient(t,e-self.WEB_INTERACTIVE_POLLING_INTERVAL)},self.WEB_INTERACTIVE_POLLING_INTERVAL))},onWebInteractiveScriptLoaded:function(t){if(window.__PRIVATE__HubspotCtaClient&&"function"==typeof window.__PRIVATE__HubspotCtaClient.loadCta){window.hsCtasOnReady=window.hsCtasOnReady||[];window.hsCtasOnReady.push(()=>{const e="#hs-cta-wrapper-"+t.placementGuid,a=document.querySelectorAll(e);a?window.__PRIVATE__HubspotCtaClient.loadCta({contentId:Number(t.webInteractiveContentId),options:{elementToEmbed:[...a]}}):console.error("Cannot find element for replacing",t)})}else console.error("Web interactive API not found after load")},renderWebInteractive:function(t,e){var a=this;if(window.__PRIVATE__HubspotCtaClient)a.onWebInteractiveScriptLoaded(t);else{const i="hubspot-web-interactives-loader",n=document.getElementById(i),s="hs-cta-embed-"+t.placementGuid;if(n){if(n.dataset.loader===s)return;a.pollForWebInteractiveClient(()=>a.onWebInteractiveScriptLoaded(t),1e4);return}const r="https://"+a.utils.getJsDomain(e.options.env,e.options.region);a.utils.addScript(r+"/web-interactives-embed.js",t.placementGuid,!0,{id:i,dataset:{hsjsPortal:t.portalId,hsjsEnv:e.options.env,hsjsHublet:e.options.region||"na1",loader:s}}).then(()=>{a.onWebInteractiveScriptLoaded(t)}).catch(t=>{console.error("Failed to load web interactive JS",{errorMessage:String(t)})})}},renderCTA:function(t){var e,a,i,n=!!document.getElementById("hs-cta-ie-element"),s=t.image_html,r=this.getTags(t),o=t.is_image;if(!n&&!o){e=document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0];a=document.createElement("style");e.insertBefore(a,e.childNodes[0]);try{i=".hs-cta-wrapper p, .hs-cta-wrapper div { margin: 0; padding: 0; }"+" "+t.css;a[document.all?"innerText":"textContent"]=i}catch(t){a.styleSheet.cssText=i}t.has_external_links&&this.addExternalCSSLinks(t.css_links,e);s=t.raw_html}for(var c=null,l=0;l-1&&"lazy"===d[g].loading&&(c=u)}if("right"==p){u.style.display="block";u.style.textAlign="right"}else if("middle"==p){u.style.display="block";u.style.textAlign="center"}u.innerHTML=s.replace("/*hs-extra-styles*/",h);u.style.visibility="visible";u.setAttribute("data-hs-drop","true");try{var m=new CustomEvent("onrenderhscta",{detail:u});document.dispatchEvent(m)}catch(t){console.error("Custom event not supported in browser.")}window.hbspt&&hbspt.cta&&hbspt.cta.afterLoad&&hbspt.cta.afterLoad(t.placement_guid)}this.trackView(t.cta_guid,t.placement_guid,c);return r},trackView:function(t,e,a){window._hsq=window._hsq||[];a?window._hsq.push((function(i){if(i.limitTrackingToCookieDomains&&!i.cookie.currentDomain||!i.trackingEnabled||i._hasDoNotTrack())self.utils.log("tracking not enabled, not tracking for: "+e+"-"+t);else{var n={k:12,aij:'["'+(e||"")+'","'+(t||"")+'"]',rfc:8},s=i._generateURL(n),r=document.createElement("img");r.src=s;r.width=1;r.height=1;r.loading="lazy";r.id="pixel-"+e+"-"+t;r.onload=function(){a.removeChild(r)};a.appendChild(r)}})):window._hsq.push(["trackCtaView",e,t])},getCtaFromService:function(t,e,a,i){for(var n=this,s=this.generateLoaderQueryParams(t,null,a,i),r=this.utils.toQueryString(s),o=0;o=0},log:function(t){if(this.isDebug()){t=(new Date).getTime()+" [CTA]: "+t;window.console&&window.console.log(t);if(this.getParameterByName("selenium")){var e=document.getElementById("selenium_log");if(!e){(e=document.createElement("pre")).id="selenium_log";document.body.appendChild(e)}e.appendChild(document.createTextNode(t+"\n"))}}},generateUtk:function(){function t(){return(65536*(1+Math.random())).toString(16).substring(0,4)}var e=(new Date).getTime().toString(16);e=e.substring(e.length-12||0,e.length);for(;e.length<12;)e="0"+e;return"c7a00000"+t()+t()+t()+e},addScript:function(t,e,a=!1,i={}){var n=document.createElement("script");n.type="text/javascript";n.async=!0;n.src=t;this.isDebug()&&this.log(e+" adding script: "+n.src.replace(/&|\?/g,"\n").replace(/=/g,"\t= "));(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).appendChild(n);if(a)return new Promise((t,e)=>{let a=!1;n.onload=()=>{a=!0;t()};n.onerror=()=>e(new Error("addScript failed for: "+src));if(i){const{dataset:t={},...e}=i;Object.keys(t).forEach(e=>{n.dataset[e]=t[e]});Object.keys(e).forEach(t=>n.setAttribute(t,e[t]))}document.getElementsByTagName("head")[0].appendChild(n);setTimeout(()=>{a||e(new Error("addScript timed out for: "+src))},1e4)})},isPreviewUrlFn:function(e){return/preview(-[^\.]+)?\.hs-sites(qa)?(-[^\.]+)?\.com/g.test(e)||/hubspotpreview(qa)?(-[^\.]+)?/.test(e)||!!t.utils.getParameterByName("hs_preview")},getRequest:function(t,e,a){var i=new XMLHttpRequest;i.onreadystatechange=function(){if(4===i.readyState){if(200===i.status)try{var t=JSON.parse(i.responseText),n="";try{n=i.getResponseHeader("x-origin-hublet")}catch(t){}e(t,n)}catch(t){a(t)}i.status>=400&&a()}};i.open("GET",t,!0);i.withCredentials=!0;i.send(null)},setTrackingEnv:function(t,e,a){this.env=t||"prod";this.hublet=e||"na1";this.portalId=a},track:function(t){var e=this.hublet||"na1",a="https://perf"+("na1"!==e?"-"+e:"")+".hsforms"+("qa"===(this.env||"prod")?"qa":"")+".com/embed/v3/counters.gif?key="+t+"&value=1";(new Image).src=a}};t.utils.isPreviewUrl=t.utils.isPreviewUrlFn(window.location.host,this.hublet);t.utils.isGooglebot=/googlebot/i.test(navigator.userAgent);t.utils.getElementsByClassName=document.getElementsByClassName?document.getElementsByClassName.bind(document):function(t){document.querySelectorAll("."+t)};t.utils.domReady((function(){t.utils.domReadyCalled=!0}))}(window.hbspt.cta); -------------------------------------------------------------------------------- /Clase 5/data/Listado de cursos - Facultad de Ciencias Sociales_files/fac_ciencias_sociales.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Clase 3/Manejo_BD_ii.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Manejo de bases de datos para las ciencias sociales II\n" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## Manipulando la base de datos \n", 15 | "\n", 16 | "- Sorting\n", 17 | "- Creación de columnas\n", 18 | "- Casting\n", 19 | "- Agregando datos\n", 20 | "- Manejando valores missing \n", 21 | "\n", 22 | "\n", 23 | "A continuación veremos cuáles son los métodos más comunes para transformar nuestra base de datos y obtener nueva información. " 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 84, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "#importando pandas y leyendo nuestros datos\n", 33 | "\n", 34 | "import pandas as pd\n" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 4, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "## Leyendo los archivos. \n", 44 | "locacion_datos = \"aqui coloca el string con la locación de tus datos\"\n", 45 | "locacion_datos = \"/Users/ccsuehara/Downloads/Datos_abiertos_admision_2021_1_2024_1.csv\" # este es el mio\n", 46 | "df = pd.read_csv(locacion_datos)" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "df.columns" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "### Ordenar nuestra base de datos:\n" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "## una base de datos en no requiere que esté ordenada, pues la información mostrada es la misma,\n", 74 | "# pero a veces es útil para visualizarla o para hacer operaciones.\n", 75 | "df = df.sort_values('ANIO_NACIMIENTO', ascending = False) # por default, ascending es True. \n", 76 | "# lo mismo, pero inplace: \n", 77 | "#df.sort_values('ANIO_NACIMIENTO', ascending = False, inplace=True)\n", 78 | "\n", 79 | "# ordenar por dos O más columnas: \n", 80 | "df = df.sort_values(by=['ANIO_NACIMIENTO', 'NACIMIENTO_PAIS'])\n", 81 | "\n", 82 | "#df = df.sort_values(by=['ANIO_NACIMIENTO', 'NACIMIENTO_PAIS'], ascending=[False, True])\n", 83 | "\n" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "metadata": {}, 89 | "source": [ 90 | "### Creando columnas nuevas. \n", 91 | "\n", 92 | "A continuación veremos varias maneras de crear variables nuevas, dependiendo de las circunstancias de los datos, así como nuestras necesidades/preferencias.\n", 93 | "\n" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": 8, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "# La manera más sencilla: \n", 103 | "# Crear una nueva columna a partir de la edad del postulante: \n", 104 | "df['MAYOR_EDAD'] = df['ANIO_NACIMIENTO'] <= 2006" 105 | ] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "metadata": {}, 110 | "source": [ 111 | "Los siguentes métodos que utilizamos para filtrar datos también sirven para crear variables: \n" 112 | ] 113 | }, 114 | { 115 | "cell_type": "markdown", 116 | "metadata": {}, 117 | "source": [ 118 | "`.loc `\n", 119 | "\n", 120 | "Podemos crear nuevas variables ubicando en el dataframe los valores que cumplen cierta condición y reemplazando por otras. " 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "df['SEXO_'] = 0\n", 130 | "df.loc[df['SEXO'] == 'FEMENINO', 'SEXO_'] = 1" 131 | ] 132 | }, 133 | { 134 | "cell_type": "markdown", 135 | "metadata": {}, 136 | "source": [ 137 | "Si queremos cambiar varias categorías a la vez, podemos utilizar `isin()`, `replace` o `where`: " 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": {}, 144 | "outputs": [], 145 | "source": [ 146 | "paises = ['ARGENTINA', 'COLOMBIA', 'VENEZUELA', 'CHILE', 'ESPAÑA',\n", 147 | " 'ITALIA', 'EE.UU.', 'BOLIVIA', 'BRAZIL', 'JAPÓN', 'KOREA',\n", 148 | " 'URUGUAY', 'ECUADOR', 'GUATEMALA', 'HONDURAS',\n", 149 | " 'SUIZA', 'SIRIA', 'PARAGUAY', 'FRANCIA', 'MÉXICO'] ## df['NACIMIENTO_PAIS'].unique()\n", 150 | "\n", 151 | "df[\"extranjero\"] = 0\n", 152 | "df.loc[df['NACIMIENTO_PAIS'].isin(), \"extranjero\"] = 1" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "df['OTRO_SEXO'] = df['SEXO']\n", 162 | "df.replace({'OTRO_SEXO': {'FEMENINO': 1, 'MASCULINO': 0}}, inplace=True)" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": 21, 168 | "metadata": {}, 169 | "outputs": [], 170 | "source": [ 171 | "# import numpy as np\n", 172 | "# df['extranjero'] = np.where(df['NACIMIENTO_PAIS'].isin(paises), 1, 0)\n" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "df.columns" 182 | ] 183 | }, 184 | { 185 | "cell_type": "markdown", 186 | "metadata": {}, 187 | "source": [ 188 | "Utilizando `eval` podemos hacerlo con una sola expresión: \n" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "df['MAYOR_EDAD'] = df.eval('ANIO_NACIMIENTO <= 2006')\n", 198 | "df['INGRESANTES_NOLIMA'] = df.eval(\"INGRESO == 'NO' & DOMICILIO_DEPA != 'LIMA'\")\n", 199 | "\n" 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "metadata": {}, 205 | "source": [ 206 | "### Una forma más general: Utilizando apply y funciones lambda. \n", 207 | "\n", 208 | "Recuerdan las funciones labmda que vimos en la clase pasada? Estas resultan muy útiles para hacer operaciones en columnas de un dataframe cuando la vectorización no es posible. A continuación veremos algunos ejemplos: " 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "metadata": {}, 215 | "outputs": [], 216 | "source": [ 217 | "df['MAYOR_EDAD_'] = df['ANIO_NACIMIENTO'].apply(lambda x: x <= 2006)\n" 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": 27, 223 | "metadata": {}, 224 | "outputs": [], 225 | "source": [ 226 | "def mayor_edad(x):\n", 227 | " if x <= 2006:\n", 228 | " return True\n", 229 | " else:\n", 230 | " return False\n", 231 | " \n", 232 | "df['MAYOR_EDAD_'] = df['ANIO_NACIMIENTO'].apply(lambda x: mayor_edad(x))" 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "metadata": {}, 238 | "source": [ 239 | "También podemos crear variables categóricas en base a variables contínuas con `cut`: " 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": 38, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "categ_labels = ['cat_1', 'cat_2', 'cat_3', 'cat_4']\n", 249 | "categ_bins = [-1, 5, 10, 15, 20.01]" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "df['cat_calificacion'] = pd.cut(df['CALIF_FINAL'],\n", 259 | " bins = categ_bins, labels = categ_labels)" 260 | ] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "metadata": {}, 265 | "source": [ 266 | "### Casting: Cambiando tipos de datos: \n", 267 | "Hay veces cuando necetaremos cambiar el tipo de dato de una columna. \n", 268 | "\n", 269 | "- Por ejemplo, cuando el csv fue leido y una columna que debería ser numérica, es leída como string. \n", 270 | "- Otra situación se da cuando queremos optimizar el uso de memoria de nuestra base de datos, y por ejemplo, queremos reducir el número de decimales que el sistema guarda. \n", 271 | "- Luego, cuando concatenamos bases de datos, los tipos entre uno y otro pueden no coincidir, y necesitaremos cambiarlos para poder hacer operaciones.\n" 272 | ] 273 | }, 274 | { 275 | "cell_type": "code", 276 | "execution_count": null, 277 | "metadata": {}, 278 | "outputs": [], 279 | "source": [ 280 | "df['ANIO_NACIMIENTO'] = df['ANIO_NACIMIENTO'].astype('str') \n", 281 | "\n", 282 | "# Cuando leemos los archivos, existe un argumento que se llama dtype, que nos permite especificar el tipo de dato de cada columna.\n" 283 | ] 284 | }, 285 | { 286 | "cell_type": "markdown", 287 | "metadata": {}, 288 | "source": [ 289 | "## Agregando datos\n", 290 | "\n", 291 | "\n", 292 | "Para hacer agregaciones por columnas: ```axis = 0``` ó ```axis = 'index' ```\n", 293 | "Para hacer agregaciones por filas: ```axis = 1``` ó ```axis = 'columns' ```\n", 294 | "\n", 295 | "(dato curioso: El axis 0 en realidad se refiere a las filas, pero lo invocamos para obtener datos agregados por columnas porque es como lo mantenemos \"fijo\". Lo mismo para hacer operaciones por filas). \n", 296 | "\n", 297 | "| Función | Descripción |\n", 298 | "|-------------|-----------------------------------------------------------|\n", 299 | "| `mean` | Calcula el promedio de los valores. |\n", 300 | "| `median` | Encuentra la mediana de los valores. |\n", 301 | "| `sum` | Suma todos los valores. |\n", 302 | "| `min` | Encuentra el valor mínimo. |\n", 303 | "| `max` | Encuentra el valor máximo. |\n", 304 | "| `quantile` | Calcula el cuantil especificado de los valores. |\n", 305 | "| `std` | Calcula la desviación estándar de los valores. |\n", 306 | "| `var` | Calcula la varianza de los valores. |\n", 307 | "| `count` | Cuenta el número de valores no nulos. |\n" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": 57, 313 | "metadata": {}, 314 | "outputs": [], 315 | "source": [ 316 | "pbi = pd.read_csv(\"datos/pbi.csv\")\n", 317 | "\n", 318 | "departamentos = ['Amazonas', 'Áncash', 'Apurímac', 'Arequipa', 'Ayacucho',\n", 319 | " 'Cajamarca', 'Cusco', 'Huancavelica', 'Huánuco', 'Ica', 'Junín',\n", 320 | " 'La Libertad', 'Lambayeque', 'Lima', 'Prov. Const. del Callao',\n", 321 | " 'Región Lima', 'Provincia de Lima', 'Loreto', 'Madre de Dios',\n", 322 | " 'Moquegua', 'Pasco', 'Piura', 'Puno', 'San Martín', 'Tacna', 'Tumbes',\n", 323 | " 'Ucayali']" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": {}, 330 | "outputs": [], 331 | "source": [ 332 | "## Hallando la suma total de pbi departamental\n", 333 | "pbi['total'] = pbi[departamentos].sum(axis=1)\n", 334 | "\n", 335 | "## Hallando el promedio de pbi departamental de los últimos años:\n", 336 | "\n", 337 | "pbi[departamentos].mean() # axis = 0 es por default. b" 338 | ] 339 | }, 340 | { 341 | "cell_type": "markdown", 342 | "metadata": {}, 343 | "source": [ 344 | "## Utilizando el groupby:\n", 345 | "\n", 346 | "El groupby nos va a permitir agrupar los datos según una columna y aplicar una función a cada grupo. Es conveniente para cuando querramos obtener datos a un nivel más agregado. " 347 | ] 348 | }, 349 | { 350 | "cell_type": "code", 351 | "execution_count": null, 352 | "metadata": {}, 353 | "outputs": [], 354 | "source": [ 355 | "df.columns" 356 | ] 357 | }, 358 | { 359 | "cell_type": "code", 360 | "execution_count": null, 361 | "metadata": {}, 362 | "outputs": [], 363 | "source": [ 364 | "df.groupby('ESPECIALIDAD')['CALIF_FINAL'].mean()\n", 365 | "#.sort_values(ascending = False)" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": null, 371 | "metadata": {}, 372 | "outputs": [], 373 | "source": [ 374 | "df.groupby(['ESPECIALIDAD', 'INGRESO'])['CALIF_FINAL'].mean()\n", 375 | "## qué pasa si colocas un .reset_index() al final? \n" 376 | ] 377 | }, 378 | { 379 | "cell_type": "markdown", 380 | "metadata": {}, 381 | "source": [ 382 | "### Una forma generalizada de hacer groupbys: " 383 | ] 384 | }, 385 | { 386 | "cell_type": "code", 387 | "execution_count": null, 388 | "metadata": {}, 389 | "outputs": [], 390 | "source": [ 391 | "\n", 392 | "## aquí utilizamos el método agg para aplicar varias funciones a la vez. \n", 393 | "nueva_agregacion =df.groupby(['ESPECIALIDAD']).agg(\n", 394 | "{'CALIF_FINAL': ['mean', 'max','min'], \n", 395 | " 'ANIO_NACIMIENTO': ['min', 'median']}\n", 396 | ")\n", 397 | "\n" 398 | ] 399 | }, 400 | { 401 | "cell_type": "code", 402 | "execution_count": null, 403 | "metadata": {}, 404 | "outputs": [], 405 | "source": [ 406 | "## los nombres de las columnas son una lista de strings, que al tener varios niveles, tendrán un multiIndex. \n", 407 | "# En este curso no lidiaaremos con multiIndex, así que te propongo la siguiente solución: \n", 408 | "\n", 409 | "nueva_agregacion.columns = [''.join(col).strip() for col in nueva_agregacion.columns.values]\n" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": null, 415 | "metadata": {}, 416 | "outputs": [], 417 | "source": [ 418 | "## Otra forma de hacerlo \n", 419 | "\n", 420 | "new_col = []\n", 421 | "for col in nueva_agregacion.columns.values:\n", 422 | " a = ''.join(col).strip()\n", 423 | " new_col.append(a)\n", 424 | "nueva_agregacion.columns = new_col\n" 425 | ] 426 | }, 427 | { 428 | "cell_type": "code", 429 | "execution_count": null, 430 | "metadata": {}, 431 | "outputs": [], 432 | "source": [ 433 | "# Otra forma de hacerlo\n", 434 | "# df.groupby(['ESPECIALIDAD', 'INGRESO']).agg(nueva_var = ('CALIF_FINAL', 'mean')).reset_index()" 435 | ] 436 | }, 437 | { 438 | "cell_type": "markdown", 439 | "metadata": {}, 440 | "source": [ 441 | "## resumiendo datos con pivot_table()\n", 442 | "Pandas tiene un método que nos permite hacer tablas dinámicas (a lo Excel) para resumir información. \n", 443 | "\n" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": null, 449 | "metadata": {}, 450 | "outputs": [], 451 | "source": [ 452 | "pd.pivot_table(df, values = 'CALIF_FINAL', #variable con los valores que vamos a resumir\n", 453 | " index = 'ESPECIALIDAD', # filas\n", 454 | " columns = 'INGRESO', # columnas\n", 455 | " aggfunc = 'mean' # función de agregación\n", 456 | " ) " 457 | ] 458 | }, 459 | { 460 | "cell_type": "code", 461 | "execution_count": null, 462 | "metadata": {}, 463 | "outputs": [], 464 | "source": [ 465 | "pd.pivot_table(df,\n", 466 | " values = ['CALIF_FINAL', 'ANIO_NACIMIENTO'],\n", 467 | " index = 'ESPECIALIDAD',\n", 468 | " columns = 'INGRESO',\n", 469 | " aggfunc = {'CALIF_FINAL': ['mean', 'median'], \n", 470 | " 'ANIO_NACIMIENTO': 'median'})" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": null, 476 | "metadata": {}, 477 | "outputs": [], 478 | "source": [ 479 | "### Formatos Long-Wide:\n", 480 | "\n" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": null, 486 | "metadata": {}, 487 | "outputs": [], 488 | "source": [ 489 | "pbi.melt(id_vars=\"Anio\") ## En caso tuviesemos más de una variable" 490 | ] 491 | }, 492 | { 493 | "cell_type": "code", 494 | "execution_count": null, 495 | "metadata": {}, 496 | "outputs": [], 497 | "source": [ 498 | "df_wide = pd.pivot_table(df, values = 'CALIF_FINAL', index = 'ESPECIALIDAD', columns = 'INGRESO', aggfunc = 'mean').reset_index()\n", 499 | "df_wide.melt(id_vars = 'ESPECIALIDAD', value_vars = ['NO', 'SI'])" 500 | ] 501 | }, 502 | { 503 | "cell_type": "markdown", 504 | "metadata": {}, 505 | "source": [ 506 | "### Manejo de datos faltantes:\n", 507 | "Los datos faltantes pueden suceder por varias razones:\n", 508 | "- Cuando no se necesita registrar los datos de dicha observación (por ejemplo, nivel educativo para menores de 3 años). \n", 509 | "- Sin embargo, esto puede afectar nuestro análisis si son errores en el levantamiento de la información. \n", 510 | " - ejemplo de variables sensibles de levantamiento. \n", 511 | " - errores de levantamiento de datos. \n", 512 | " \n", 513 | "Su identifcación y tratamiento es importante. \n" 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "execution_count": null, 519 | "metadata": {}, 520 | "outputs": [], 521 | "source": [ 522 | "## IDentificando datos faltantes:\n", 523 | "df.isna().sum() # nos da la cantidad de datos faltantes por columna." 524 | ] 525 | }, 526 | { 527 | "cell_type": "code", 528 | "execution_count": null, 529 | "metadata": {}, 530 | "outputs": [], 531 | "source": [ 532 | "## Observando datos faltantes de un subconjunto de columnas:\n", 533 | "df[['COLEGIO_DEPA', 'NACIMIENTO_DEPA']].isna().sum()\n", 534 | "\n", 535 | "df = df.fillna(0) # reemplaza los datos faltantes por 0.\n", 536 | "# \n", 537 | "df[['COLEGIO_DEPA', 'NACIMIENTO_DEPA']].fillna('No especificado')\n", 538 | "\n", 539 | "# Otros métodos: notna(), dropna() \n" 540 | ] 541 | } 542 | ], 543 | "metadata": { 544 | "kernelspec": { 545 | "display_name": "strmlt", 546 | "language": "python", 547 | "name": "python3" 548 | }, 549 | "language_info": { 550 | "codemirror_mode": { 551 | "name": "ipython", 552 | "version": 3 553 | }, 554 | "file_extension": ".py", 555 | "mimetype": "text/x-python", 556 | "name": "python", 557 | "nbconvert_exporter": "python", 558 | "pygments_lexer": "ipython3", 559 | "version": "3.12.3" 560 | } 561 | }, 562 | "nbformat": 4, 563 | "nbformat_minor": 2 564 | } 565 | -------------------------------------------------------------------------------- /Clase 4/Manejo_BD_ii.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Manejo de bases de datos para las ciencias sociales II\n" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## Manipulando la base de datos \n", 15 | "\n", 16 | "- [Sorting](#sorting)\n", 17 | "- [Creación de columnas](#create)\n", 18 | "- [Casting](#casting)\n", 19 | "- [Agregando datos](#agg)\n", 20 | "- [Resumiento datos](#resumiendo-datos-con-pivot_table)\n", 21 | "- [Manejando valores faltantes](#missing)\n", 22 | "\n", 23 | "A continuación veremos cuáles son los métodos más comunes para transformar nuestra base de datos y obtener nueva información. " 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 84, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "#importando pandas y leyendo nuestros datos\n", 33 | "\n", 34 | "import pandas as pd\n" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 4, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "## Leyendo los archivos. \n", 44 | "locacion_datos = \"aqui coloca el string con la locación de tus datos\"\n", 45 | "locacion_datos = \"/Users/ccsuehara/Downloads/Datos_abiertos_admision_2021_1_2024_1.csv\" # este es el mio\n", 46 | "df = pd.read_csv(locacion_datos)" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "df.columns" 56 | ] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "metadata": {}, 61 | "source": [ 62 | " \n", 63 | "\n", 64 | "### Ordenar nuestra base de datos:\n" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "## una base de datos en no requiere que esté ordenada, pues la información mostrada es la misma,\n", 74 | "# pero a veces es útil para visualizarla o para hacer operaciones.\n", 75 | "df = df.sort_values('ANIO_NACIMIENTO', ascending = False) # por default, ascending es True. \n", 76 | "# lo mismo, pero inplace: \n", 77 | "#df.sort_values('ANIO_NACIMIENTO', ascending = False, inplace=True)\n", 78 | "\n", 79 | "# ordenar por dos O más columnas: \n", 80 | "df = df.sort_values(by=['ANIO_NACIMIENTO', 'NACIMIENTO_PAIS'])\n", 81 | "\n", 82 | "#df = df.sort_values(by=['ANIO_NACIMIENTO', 'NACIMIENTO_PAIS'], ascending=[False, True])\n", 83 | "\n" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "metadata": {}, 89 | "source": [ 90 | " \n", 91 | "\n", 92 | "### Creando columnas nuevas. \n", 93 | "\n", 94 | "A continuación veremos varias maneras de crear variables nuevas, dependiendo de las circunstancias de los datos, así como nuestras necesidades/preferencias.\n", 95 | "\n" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 8, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "# La manera más sencilla: \n", 105 | "# Crear una nueva columna a partir de la edad del postulante: \n", 106 | "df['MAYOR_EDAD'] = df['ANIO_NACIMIENTO'] <= 2006" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": {}, 112 | "source": [ 113 | "Los siguentes métodos que utilizamos para filtrar datos también sirven para crear variables: \n" 114 | ] 115 | }, 116 | { 117 | "cell_type": "markdown", 118 | "metadata": {}, 119 | "source": [ 120 | "`.loc `\n", 121 | "\n", 122 | "Podemos crear nuevas variables ubicando en el dataframe los valores que cumplen cierta condición y reemplazando por otras. " 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "df['SEXO_'] = 0\n", 132 | "df.loc[df['SEXO'] == 'FEMENINO', 'SEXO_'] = 1" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "Si queremos cambiar varias categorías a la vez, podemos utilizar `isin()`, `replace` o `where`: " 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "paises = ['ARGENTINA', 'COLOMBIA', 'VENEZUELA', 'CHILE', 'ESPAÑA',\n", 149 | " 'ITALIA', 'EE.UU.', 'BOLIVIA', 'BRAZIL', 'JAPÓN', 'KOREA',\n", 150 | " 'URUGUAY', 'ECUADOR', 'GUATEMALA', 'HONDURAS',\n", 151 | " 'SUIZA', 'SIRIA', 'PARAGUAY', 'FRANCIA', 'MÉXICO'] ## df['NACIMIENTO_PAIS'].unique()\n", 152 | "\n", 153 | "df[\"extranjero\"] = 0\n", 154 | "df.loc[df['NACIMIENTO_PAIS'].isin(), \"extranjero\"] = 1" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "df['OTRO_SEXO'] = df['SEXO']\n", 164 | "df.replace({'OTRO_SEXO': {'FEMENINO': 1, 'MASCULINO': 0}}, inplace=True)" 165 | ] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": 21, 170 | "metadata": {}, 171 | "outputs": [], 172 | "source": [ 173 | "# import numpy as np\n", 174 | "# df['extranjero'] = np.where(df['NACIMIENTO_PAIS'].isin(paises), 1, 0)\n" 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": null, 180 | "metadata": {}, 181 | "outputs": [], 182 | "source": [ 183 | "df.columns" 184 | ] 185 | }, 186 | { 187 | "cell_type": "markdown", 188 | "metadata": {}, 189 | "source": [ 190 | "Utilizando `eval` podemos hacerlo con una sola expresión: \n" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": null, 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "df['MAYOR_EDAD'] = df.eval('ANIO_NACIMIENTO <= 2006')\n", 200 | "df['INGRESANTES_NOLIMA'] = df.eval(\"INGRESO == 'NO' & DOMICILIO_DEPA != 'LIMA'\")\n", 201 | "\n" 202 | ] 203 | }, 204 | { 205 | "cell_type": "markdown", 206 | "metadata": {}, 207 | "source": [ 208 | "### Una forma más general: Utilizando apply y funciones lambda. \n", 209 | "\n", 210 | "Recuerdan las funciones labmda que vimos en la clase pasada? Estas resultan muy útiles para hacer operaciones en columnas de un dataframe cuando la vectorización no es posible. A continuación veremos algunos ejemplos: " 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "df['MAYOR_EDAD_'] = df['ANIO_NACIMIENTO'].apply(lambda x: x <= 2006)\n" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": 27, 225 | "metadata": {}, 226 | "outputs": [], 227 | "source": [ 228 | "def mayor_edad(x):\n", 229 | " if x <= 2006:\n", 230 | " return True\n", 231 | " else:\n", 232 | " return False\n", 233 | " \n", 234 | "df['MAYOR_EDAD_'] = df['ANIO_NACIMIENTO'].apply(lambda x: mayor_edad(x))\n", 235 | "\n", 236 | "# A continuación, vamos a limpiar un poco los datos del departamento de nacimiento.\n", 237 | "def str_replace(txt):\n", 238 | " return txt.replace(\"á\", \"a\").replace(\"é\", \"e\").replace(\"í\", \"i\").replace(\n", 239 | " \"ó\", \"o\").replace(\"ú\", \"u\").replace(\"Á\", \"A\").replace('Prov. Const. del Callao', 'Callao')" 240 | ] 241 | }, 242 | { 243 | "cell_type": "markdown", 244 | "metadata": {}, 245 | "source": [ 246 | "También podemos crear variables categóricas en base a variables contínuas con `cut`: " 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": 38, 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "categ_labels = ['cat_1', 'cat_2', 'cat_3', 'cat_4']\n", 256 | "categ_bins = [-1, 5, 10, 15, 20.01]" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": null, 262 | "metadata": {}, 263 | "outputs": [], 264 | "source": [ 265 | "df['cat_calificacion'] = pd.cut(df['CALIF_FINAL'],\n", 266 | " bins = categ_bins, labels = categ_labels)" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "metadata": {}, 273 | "outputs": [], 274 | "source": [ 275 | "df['DOMICILIO_DEPA'] = df['DOMICILIO_DEPA'].apply(lambda x: str_replace(x))\n" 276 | ] 277 | }, 278 | { 279 | "cell_type": "markdown", 280 | "metadata": {}, 281 | "source": [ 282 | " \n", 283 | "\n", 284 | "### Casting: Cambiando tipos de datos: \n", 285 | "Hay veces cuando necetaremos cambiar el tipo de dato de una columna. \n", 286 | "\n", 287 | "- Por ejemplo, cuando el csv fue leido y una columna que debería ser numérica, es leída como string. \n", 288 | "- Otra situación se da cuando queremos optimizar el uso de memoria de nuestra base de datos, y por ejemplo, queremos reducir el número de decimales que el sistema guarda. \n", 289 | "- Luego, cuando concatenamos bases de datos, los tipos entre uno y otro pueden no coincidir, y necesitaremos cambiarlos para poder hacer operaciones.\n" 290 | ] 291 | }, 292 | { 293 | "cell_type": "code", 294 | "execution_count": null, 295 | "metadata": {}, 296 | "outputs": [], 297 | "source": [ 298 | "df['ANIO_NACIMIENTO'] = df['ANIO_NACIMIENTO'].astype('str') \n", 299 | "\n", 300 | "# Cuando leemos los archivos, existe un argumento que se llama dtype, que nos permite especificar el tipo de dato de cada columna.\n" 301 | ] 302 | }, 303 | { 304 | "cell_type": "markdown", 305 | "metadata": {}, 306 | "source": [ 307 | " \n", 308 | "\n", 309 | "### Agregando datos\n", 310 | "\n", 311 | "\n", 312 | "Para hacer agregaciones por columnas: ```axis = 0``` ó ```axis = 'index' ```\n", 313 | "Para hacer agregaciones por filas: ```axis = 1``` ó ```axis = 'columns' ```\n", 314 | "\n", 315 | "(dato curioso: El axis 0 en realidad se refiere a las filas, pero lo invocamos para obtener datos agregados por columnas porque es como lo mantenemos \"fijo\". Lo mismo para hacer operaciones por filas). \n", 316 | "\n", 317 | "| Función | Descripción |\n", 318 | "|-------------|-----------------------------------------------------------|\n", 319 | "| `mean` | Calcula el promedio de los valores. |\n", 320 | "| `median` | Encuentra la mediana de los valores. |\n", 321 | "| `sum` | Suma todos los valores. |\n", 322 | "| `min` | Encuentra el valor mínimo. |\n", 323 | "| `max` | Encuentra el valor máximo. |\n", 324 | "| `quantile` | Calcula el cuantil especificado de los valores. |\n", 325 | "| `std` | Calcula la desviación estándar de los valores. |\n", 326 | "| `var` | Calcula la varianza de los valores. |\n", 327 | "| `count` | Cuenta el número de valores no nulos. |\n" 328 | ] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": 57, 333 | "metadata": {}, 334 | "outputs": [], 335 | "source": [ 336 | "pbi = pd.read_csv(\"datos/pbi.csv\")\n", 337 | "\n", 338 | "departamentos = ['Amazonas', 'Áncash', 'Apurímac', 'Arequipa', 'Ayacucho',\n", 339 | " 'Cajamarca', 'Cusco', 'Huancavelica', 'Huánuco', 'Ica', 'Junín',\n", 340 | " 'La Libertad', 'Lambayeque', 'Lima', 'Prov. Const. del Callao',\n", 341 | " 'Región Lima', 'Provincia de Lima', 'Loreto', 'Madre de Dios',\n", 342 | " 'Moquegua', 'Pasco', 'Piura', 'Puno', 'San Martín', 'Tacna', 'Tumbes',\n", 343 | " 'Ucayali']" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": null, 349 | "metadata": {}, 350 | "outputs": [], 351 | "source": [ 352 | "## Hallando la suma total de pbi departamental\n", 353 | "pbi['total'] = pbi[departamentos].sum(axis=1)\n", 354 | "\n", 355 | "## Hallando el promedio de pbi departamental de los últimos años:\n", 356 | "\n", 357 | "pbi[departamentos].mean() # axis = 0 es por default. b" 358 | ] 359 | }, 360 | { 361 | "cell_type": "markdown", 362 | "metadata": {}, 363 | "source": [ 364 | "#### Utilizando el groupby:\n", 365 | "\n", 366 | "El groupby nos va a permitir agrupar los datos según una columna y aplicar una función a cada grupo. Es conveniente para cuando querramos obtener datos a un nivel más agregado. " 367 | ] 368 | }, 369 | { 370 | "cell_type": "code", 371 | "execution_count": null, 372 | "metadata": {}, 373 | "outputs": [], 374 | "source": [ 375 | "df.columns" 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": null, 381 | "metadata": {}, 382 | "outputs": [], 383 | "source": [ 384 | "df.groupby('ESPECIALIDAD')['CALIF_FINAL'].mean()\n", 385 | "#.sort_values(ascending = False)" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": null, 391 | "metadata": {}, 392 | "outputs": [], 393 | "source": [ 394 | "df.groupby(['ESPECIALIDAD', 'INGRESO'])['CALIF_FINAL'].mean()\n", 395 | "## qué pasa si colocas un .reset_index() al final? \n" 396 | ] 397 | }, 398 | { 399 | "cell_type": "markdown", 400 | "metadata": {}, 401 | "source": [ 402 | "### Una forma generalizada de hacer groupbys: " 403 | ] 404 | }, 405 | { 406 | "cell_type": "code", 407 | "execution_count": null, 408 | "metadata": {}, 409 | "outputs": [], 410 | "source": [ 411 | "\n", 412 | "## aquí utilizamos el método agg para aplicar varias funciones a la vez. \n", 413 | "nueva_agregacion =df.groupby(['ESPECIALIDAD']).agg(\n", 414 | "{'CALIF_FINAL': ['mean', 'max','min'], \n", 415 | " 'ANIO_NACIMIENTO': ['min', 'median']}\n", 416 | ")\n", 417 | "\n" 418 | ] 419 | }, 420 | { 421 | "cell_type": "code", 422 | "execution_count": null, 423 | "metadata": {}, 424 | "outputs": [], 425 | "source": [ 426 | "## los nombres de las columnas son una lista de strings, que al tener varios niveles, tendrán un multiIndex. \n", 427 | "# En este curso no lidiaaremos con multiIndex, así que te propongo la siguiente solución: \n", 428 | "\n", 429 | "nueva_agregacion.columns = [''.join(col).strip() for col in nueva_agregacion.columns.values]\n" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": null, 435 | "metadata": {}, 436 | "outputs": [], 437 | "source": [ 438 | "## Otra forma de hacerlo \n", 439 | "\n", 440 | "new_col = []\n", 441 | "for col in nueva_agregacion.columns.values:\n", 442 | " a = ''.join(col).strip()\n", 443 | " new_col.append(a)\n", 444 | "nueva_agregacion.columns = new_col\n" 445 | ] 446 | }, 447 | { 448 | "cell_type": "code", 449 | "execution_count": null, 450 | "metadata": {}, 451 | "outputs": [], 452 | "source": [ 453 | "# Otra forma de hacerlo\n", 454 | "# df.groupby(['ESPECIALIDAD', 'INGRESO']).agg(nueva_var = ('CALIF_FINAL', 'mean')).reset_index()" 455 | ] 456 | }, 457 | { 458 | "cell_type": "markdown", 459 | "metadata": {}, 460 | "source": [ 461 | "\n", 462 | "### resumiendo datos con pivot_table()\n", 463 | "Pandas tiene un método que nos permite hacer tablas dinámicas (a lo Excel) para resumir información. \n", 464 | "\n" 465 | ] 466 | }, 467 | { 468 | "cell_type": "code", 469 | "execution_count": null, 470 | "metadata": {}, 471 | "outputs": [], 472 | "source": [ 473 | "df['OTRO_SEXO'] = df['SEXO']\n", 474 | "df.replace({'OTRO_SEXO': {'FEMENINO': 1, 'MASCULINO': 0}}, inplace=True)" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": {}, 481 | "outputs": [], 482 | "source": [ 483 | "pd.pivot_table(df, values = 'CALIF_FINAL', #variable con los valores que vamos a resumir\n", 484 | " index = 'ESPECIALIDAD', # filas\n", 485 | " columns = 'INGRESO', # columnas\n", 486 | " aggfunc = 'mean' # función de agregación\n", 487 | " ) " 488 | ] 489 | }, 490 | { 491 | "cell_type": "code", 492 | "execution_count": null, 493 | "metadata": {}, 494 | "outputs": [], 495 | "source": [ 496 | "pd.pivot_table(df,\n", 497 | " values = ['CALIF_FINAL', 'ANIO_NACIMIENTO'],\n", 498 | " index = 'ESPECIALIDAD',\n", 499 | " columns = 'INGRESO',\n", 500 | " aggfunc = {'CALIF_FINAL': ['mean', 'median'], \n", 501 | " 'ANIO_NACIMIENTO': 'median'})" 502 | ] 503 | }, 504 | { 505 | "cell_type": "markdown", 506 | "metadata": {}, 507 | "source": [ 508 | "### Formatos Long-Wide:\n", 509 | "\n", 510 | "" 511 | ] 512 | }, 513 | { 514 | "cell_type": "code", 515 | "execution_count": null, 516 | "metadata": {}, 517 | "outputs": [], 518 | "source": [ 519 | "# ejemplo de wide a long: \n", 520 | "\n", 521 | "pbi.melt(id_vars=\"Anio\") ## En caso tuviesemos más de una variable" 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": null, 527 | "metadata": {}, 528 | "outputs": [], 529 | "source": [ 530 | "#ejemplo de long a wide \n", 531 | "df_wide = pd.pivot_table(df, values = 'CALIF_FINAL', index = 'ESPECIALIDAD', columns = 'INGRESO', aggfunc = 'mean').reset_index()\n", 532 | "#ejemplo de wide a long\n", 533 | "df_wide.melt(id_vars = 'ESPECIALIDAD', value_vars = ['NO', 'SI'])" 534 | ] 535 | }, 536 | { 537 | "cell_type": "markdown", 538 | "metadata": {}, 539 | "source": [ 540 | " \n", 541 | "\n", 542 | "### Manejo de datos faltantes:\n", 543 | "Los datos faltantes pueden suceder por varias razones:\n", 544 | "- Cuando no se necesita registrar los datos de dicha observación (por ejemplo, nivel educativo para menores de 3 años). \n", 545 | "- Sin embargo, esto puede afectar nuestro análisis si son errores en el levantamiento de la información. \n", 546 | " - ejemplo de variables sensibles de levantamiento. \n", 547 | " - errores de levantamiento de datos. \n", 548 | " \n", 549 | "Su identifcación y tratamiento es importante. \n" 550 | ] 551 | }, 552 | { 553 | "cell_type": "code", 554 | "execution_count": null, 555 | "metadata": {}, 556 | "outputs": [], 557 | "source": [ 558 | "## IDentificando datos faltantes:\n", 559 | "df.isna().sum() # nos da la cantidad de datos faltantes por columna." 560 | ] 561 | }, 562 | { 563 | "cell_type": "code", 564 | "execution_count": null, 565 | "metadata": {}, 566 | "outputs": [], 567 | "source": [ 568 | "## Observando datos faltantes de un subconjunto de columnas:\n", 569 | "df[['COLEGIO_DEPA', 'NACIMIENTO_DEPA']].isna().sum()\n", 570 | "\n", 571 | "df = df.fillna(0) # reemplaza los datos faltantes por 0.\n", 572 | "# \n", 573 | "df[['COLEGIO_DEPA', 'NACIMIENTO_DEPA']].fillna('No especificado')\n", 574 | "\n", 575 | "# Otros métodos: notna(), dropna() \n" 576 | ] 577 | } 578 | ], 579 | "metadata": { 580 | "kernelspec": { 581 | "display_name": "strmlt", 582 | "language": "python", 583 | "name": "python3" 584 | }, 585 | "language_info": { 586 | "codemirror_mode": { 587 | "name": "ipython", 588 | "version": 3 589 | }, 590 | "file_extension": ".py", 591 | "mimetype": "text/x-python", 592 | "name": "python", 593 | "nbconvert_exporter": "python", 594 | "pygments_lexer": "ipython3", 595 | "version": "3.12.3" 596 | } 597 | }, 598 | "nbformat": 4, 599 | "nbformat_minor": 2 600 | } 601 | --------------------------------------------------------------------------------