Data Science N029. numpy Matrices
hive-154226·@rafaelaquino·
0.000 HBDData Science N029. numpy Matrices
Cordiales saludos <center>  </center> Comencemos entrando a nuestro entorno virtual y luego ejecutando ```jupyter lab``` ``` rafael@HP:~$ rafael@HP:~$ cd .gitlab/datascience/ rafael@HP:~/.gitlab/datascience$ rafael@HP:~/.gitlab/datascience$ source env/bin/activate (env) rafael@HP:~/.gitlab/datascience$ (env) rafael@HP:~/.gitlab/datascience$ jupyter lab ``` Para comenzar importamos la librería de **numpy** <center>  </center> ```python import numpy as np ``` ## Generar una matriz con un rango de fecha Podemos crear un rango de fecha en formato de dos dimensiones. ```python np.arange('2024-01', '2024-02', dtype='datetime64[D]') ``` ``` array(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08', '2024-01-09', '2024-01-10', '2024-01-11', '2024-01-12', '2024-01-13', '2024-01-14', '2024-01-15', '2024-01-16', '2024-01-17', '2024-01-18', '2024-01-19', '2024-01-20', '2024-01-21', '2024-01-22', '2024-01-23', '2024-01-24', '2024-01-25', '2024-01-26', '2024-01-27', '2024-01-28', '2024-01-29', '2024-01-30', '2024-01-31'], dtype='datetime64[D]') ``` ## Matriz identidad Otra forma de generar la matriz identidad es con ```np.eye()``` ```python np.eye(4, dtype=int) ``` ``` array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) ``` ```python np.eye(4) array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) ``` ## Repaso matriz Identidad Esta forma de generar la matriz identidad ya la habíamos visto en este curso ```python np.identity(4) ``` array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) ```python np.identity(4, dtype=int) ``` array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) ## randint Podemos generar una matriz con números aleatorios, en este caso generamos una matriz de 5 por 5 con números aleatorios entre el 1 y 10. ```python np.random.randint(1,10,(5,5)) ``` array([[9, 1, 5, 3, 6], [2, 1, 9, 9, 1], [2, 6, 7, 3, 9], [2, 1, 1, 6, 9], [2, 2, 2, 2, 1]]) ## Suma de matrices Con ```np.random.randint()``` generamos dos matrices para realizar la suma de matrices. ```python matriz = np.random.randint(1,50,(3,3)) matriz ``` array([[17, 8, 37], [12, 2, 27], [41, 21, 25]]) ```python matriz2 = np.random.randint(1,50,(3,3)) matriz2 ``` array([[ 9, 16, 40], [43, 27, 33], [ 2, 39, 33]]) ## Sumando matriz + matriz2 Con el concepto de *suma de matrices* se realiza la operación de sumar cada uno de sus elementos. ```python matriz + matriz2 ``` array([[26, 24, 77], [55, 29, 60], [43, 60, 58]]) ## max(), min(),sum() Podemos encontrar el máximo valor de la matriz; el menor valor de la matriz y la suma de todos sus valores. ```python matriz3 = np.random.randint(1,50,(3,3)) matriz3 ``` array([[ 6, 18, 25], [ 7, 35, 48], [35, 31, 9]]) ```python matriz3.max() ``` 48 ```python matriz3.min() ``` 6 ```python matriz3.sum() ``` 214 ## Ejercicios Varios ```python lista=([ [1,2,3],[4,5,6] ]) m=np.array(lista) m ``` array([[1, 2, 3], [4, 5, 6]]) ```python m2=np.array([ [10,20,30],[40,50,60], [70,80,90] ]) m2 ``` array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) ###### Matriz diagonal ```python m3=np.diag(np.diag(m2)) m3 ``` array([[10, 0, 0], [ 0, 50, 0], [ 0, 0, 90]]) ```python m4=np.diag([1,2,3,4,5,6,7,8]) m4 ``` array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0], [0, 0, 0, 0, 0, 6, 0, 0], [0, 0, 0, 0, 0, 0, 7, 0], [0, 0, 0, 0, 0, 0, 0, 8]]) ```python m4.shape ``` (8, 8) ###### Creando matrices con full() ```python m5=np.full((3,3),100) m5 ``` array([[100, 100, 100], [100, 100, 100], [100, 100, 100]]) ###### Creando matrices con ones() ```python m6=np.ones((3,3)) m6 ``` array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]) ```python m7=np.ones((3,3), dtype=int) m7 ``` array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) ###### Creando matrices con zeros() ```python m8=np.zeros((3,3)) m8 ``` array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) ```python m9=np.zeros((3,3), dtype=int) m9 ``` array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) ###### Creando matrices con arange() ```python m10=np.array([np.arange(4),np.arange(4)]) m10 ``` array([[0, 1, 2, 3], [0, 1, 2, 3]]) ```python list1=np.arange(3) list2=np.arange(3) m11=np.array([list1,list2]) m11 ``` array([[0, 1, 2], [0, 1, 2]]) ###### Subarrreglos ```python m12 = np.array([ [9,8,7,6], [5,4,3,2] ]) m12 ``` array([[9, 8, 7, 6], [5, 4, 3, 2]]) ```python m12[1] ``` array([5, 4, 3, 2]) ```python m12[:,0] ``` array([9, 5]) ###### Posiciones (selección de valores) ```python m12[0,0] ``` 9 ```python m12[0,1] ``` 8 ``` ``` --- En esta publicacíón se repasaron temas anteriores que puedes revisar en: ✅ [Arreglos Bidimensionales](https://peakd.com/hive-154226/@rafaelaquino/data-science-n015-numpy-arreglos-bidimensionales) ✅ [Arreglos Bidimensionales - continuación](https://peakd.com/hive-154226/@rafaelaquino/data-science-n016-numpy-arreglos-bidimensionales-continuacion) ## Ampliando conocimientos Todo el código generado en **Markdown** para esta publicación lo realicé de la siguiente manera. <center>  </center> ## Actualizando el repositorio Este apartado te permite practicar git. Poco a poco de darás cuenta de la utilidad y lo importante para trabajar en este mundo de la programación e informática. ~~~ (env) rafael@HP:~/.gitlab/datascience$ (env) rafael@HP:~/.gitlab/datascience$ git status En la rama main Tu rama está actualizada con 'origin/main'. Archivos sin seguimiento: (usa "git add <archivo>..." para incluirlo a lo que se será confirmado) 29_ejercicios.ipynb no hay nada agregado al commit pero hay archivos sin seguimiento presentes (usa "git add" para hacerles seguimiento) (env) rafael@HP:~/.gitlab/datascience$ git add 29_ejercicios.ipynb (env) rafael@HP:~/.gitlab/datascience$ (env) rafael@HP:~/.gitlab/datascience$ git commit -m "add 29_ejercicios" [main 6ceba72] add 29_ejercicios 1 file changed, 870 insertions(+) create mode 100644 29_ejercicios.ipynb (env) rafael@HP:~/.gitlab/datascience$ git push Username for xxxxxxxxxxxxxxxxxxxx Password for xxxxxxxxxxxxxxxxxxxx Enumerando objetos: 4, listo. Contando objetos: 100% (4/4), listo. Compresión delta usando hasta 4 hilos Comprimiendo objetos: 100% (3/3), listo. Escribiendo objetos: 100% (3/3), 3.20 KiB | 1.60 MiB/s, listo. Total 3 (delta 1), reusados 0 (delta 0), pack-reusados 0 To https://gitlab.com/btcsiraquino/datascience.git 74f5cdb..6ceba72 main -> main (env) rafael@HP:~/.gitlab/datascience$ ~~~ Hasta aquí nuestra publicación, hasta la próxima semana. --- Para ver todas la publicaciones del Curso de Data Science, puedes entrar a: 📍 https://siraquino.github.io/pythoncumanes/datascience.html Todos a programar! [Rafael Aquino](https://twitter.com/Rafa_elaquino) Bogotá / Colombia
👍 amaponian, deadleaf, toronyor, sbi7, sbi-tokens, sneakyninja, mastergerund, thedailysneak, cryptoknight12, pixelfan, aurodivys, felixmarranz, ubaldonet, visualblock, popurri, abeba, franciscomarval, laradio, mercmarg, cleydimar2000, alberto0607, trouvaille, yenmendt, susurrodmisterio, ijelady, paolasinaid, avellana, radiosteemit, lagitana, lfu-radio, radiohive, kvfm, radiolovers, junydoble, victor816, bea23, edinson001, helencct, fabianar25, ronymaffi, ciudadcreativa, lmvc, lmvc-spaco, marijo-rm, omarmontes, joeyarnoldvn, lemouth, steemstem-trig, steemstem, roelandp, dna-replication, stemsocial, minnowbooster, howo, aboutcoolscience, robotics101, tsoldovieri, splash-of-angs63, r00sj3, francostem, de-stem, blackdaisyft, metabs, curie, techslut, walterjay, samminator, alexander.alexis, khalil319, postpromoter, madridbg, sco, alexdory, melvin7, deholt, nattybongo, pboulet, pinkfloyd878, sam9999, lamouthe, edb, mobbs, mahdiyari, aidefr, kenadis, stem.witness, prosocialise, zonguin, enzor, geopolis, croctopus, gadrian, meanbees, temitayo-pelumi, noelyss, cloh76, valth, dhimmel, sustainablyyours, helo, abigail-dantes, sorin.cristescu, intrepidphotos, fragmentarion, emiliomoron, charitybot, doctor-cog-diss, cubapl, crowdwitness, waivio.curator, hijosdelhombre, dcrops, cnfund, justyy, florian-glechner, charitymemes, kristall97, deveney, qberry, bambinaacida, m0rt0nmattd, sidalim88, syh7758520, sumant, punchline, gohive, abu78, iansart, investingpennies, steemwizards, notb4mycoffee, thelordsharvest, communitybank, utube, sportscontest, fantasycrypto, photohunt, superlotto, citizendog, steemstorage, gunthertopp, greddyforce, felt.buzz, jmsansan, migka, arunava, takowi, meritocracy, mayberlys, steveconnor, movingman, therising, double-negative, vickoly, detlev, mugueto2022, rocky1, kylealex, r-nyn, laviesm, blingit, dandesign86, bscrypto, achimmertens, irgendwo, johndeeback, cuzimgleb, rtron86, mayorkeys, enjar, ledgar, archangel21, rt395, metroair, cheese4ead, kiaazad, minerthreat, earn.vote, drawmeaship, steemean, precarious, high8125theta, swayzilla, neumannsalva, jjerryhan, michelmake, bflanagin, yunnie, sbtofficial, kevinwong, sgt-dan, carn, failingforwards, bartosz546, empath, quinnertronics, jayna, rhemagames, princessmewmew, neneandy, putu300, drricksanchez, greenforever, revo, iskafan, thelittlebank, baltai, federacion45, pandasquad, armandosodano, boxcarblue, meno, fineartnow, laxam, anttn, yixn, thecryptodrive, modernzorker, fatman, voter002, cliffagreen, sarashew, aries90, bitrocker2020, sunsea, azj26, tfeldman, stayoutoftherz, steemcryptosicko, zyx066, humbe, dynamicrypto, marc-allaria, goblinknackers, capp, apendix1994, brianoflondon, apshamilton, hamismsf, jpbliberty, podping, soyjoselopez, rmach, mcsvi, firstamendment, ibt-survival, elevator09, cloudspyder, sanderjansenart, primersion, cryptojiang, hiddendragon, markwannabee, reggaesteem, dechuck, holovision.cash, martinthemass, mr-rent, mafufuma, vindiesel1980, lordvader, pladozero, atheistrepublic, lightpaintershub, jerrybanfield, smariam, cryptictruth, juecoree, stem-espanol, lorenzor, ufv, iamphysical, azulear, sandracarrascal, ydavgonzalez, miguelangel2801, delpilar, tomastonyperez, elvigia, josedelacruz, erickyoussif, acont, reinaseq, fran.frey, aleestra, zeruxanime, peniel2010, inthenow, bartheek, andrick, uche-nna, giulyfarci52, newton666, hk-curation, hashkings, pepeymeli, marsupia, liuke96player, infernalcoliseum, rondonshneezy, fefe99, psicoluigi, walterprofe, aaronkroeblinger, scruffy23, acousticguitar, sardrt, safrizal.mus, vaultec, nfttunz, eric-boucher, robertbira, eliaschess333, esthersanchez, ajfernandez, amansharma555, orlandogonzalez, cyprianj, gifty-e, privex, ennyta, endopediatria, dandays, feltoxxx, cybercity, bluefinstudios, agileautomation, sofiaquino98, gamersclassified, tecnoticias, amigoponc,