I python Numpy matrices codificacion y manejo

29
clasespythoncientifico (/github/gfrubi/clasespythoncientifico/tree/master) / Lecture2Numpy.ipynb (/github/gfrubi/clasespythoncientifico/tree/master/Lecture2 Numpy.ipynb) Numpy arreglos de datos multidimensionales Versión original en inglés de J.R. Johansson ([email protected]) http://dml.riken.jp/~rob/ (http://dml.riken.jp/~rob/) Traducido/Adaptado por G.F. Rubilar (http://google.com/+GuillermoRubilar) . La última versión de estos notebooks de IPython (http://ipython.org/notebook.html) está disponible en http://github.com/gfrubi/clasespythoncientifico (http://github.com/gfrubi/clasespythoncientifico) . La última versión del original (en inglés) de estos notebooks de IPython (http://ipython.org/notebook.html) está disponible en http://github.com/jrjohansson/scientificpythonlectures (http://github.com/jrjohansson/scientificpythonlectures) . Los otros notebooks de esta serie están listados en http://jrjohansson.github.com (http://jrjohansson.github.com) . In [186]: # ¿qué hace esta línea?. La respuesta en la clase 4 %matplotlib inline from matplotlib.pyplot import * Introducción El paquete (módulo) numpy es usado en casi todos los cálculos numéricos usando Python. Es un paquete que provee a Python de estructuras de datos vectoriales, matriciales, y de rango mayor, de alto rendimiento. Está implementado en C y Fortran, de modo que cuando los cálculos son vectorizados (formulados con vectores y matrices), el rendimiento es muy bueno. Para usar numpy necesitamos importar el módulo usando, por ejemplo: In [187]: from numpy import * En el paquete numpy la terminología usada para vectores, matrices y conjuntos de

description

codificacion Ipython carray y matrices

Transcript of I python Numpy matrices codificacion y manejo

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 1/29

    clasespythoncientifico(/github/gfrubi/clasespythoncientifico/tree/master)/ Lecture2Numpy.ipynb(/github/gfrubi/clasespythoncientifico/tree/master/Lecture2Numpy.ipynb)

    NumpyarreglosdedatosmultidimensionalesVersinoriginaleninglsdeJ.R.Johansson([email protected])http://dml.riken.jp/~rob/(http://dml.riken.jp/~rob/)

    Traducido/AdaptadoporG.F.Rubilar(http://google.com/+GuillermoRubilar).

    LaltimaversindeestosnotebooksdeIPython(http://ipython.org/notebook.html)estdisponibleenhttp://github.com/gfrubi/clasespythoncientifico(http://github.com/gfrubi/clasespythoncientifico).

    Laltimaversindeloriginal(eningls)deestosnotebooksdeIPython(http://ipython.org/notebook.html)estdisponibleenhttp://github.com/jrjohansson/scientificpythonlectures(http://github.com/jrjohansson/scientificpythonlectures).

    Losotrosnotebooksdeestaserieestnlistadosenhttp://jrjohansson.github.com(http://jrjohansson.github.com).

    In[186]: #quhaceestalnea?.Larespuestaenlaclase4%matplotlibinlinefrommatplotlib.pyplotimport*

    IntroduccinElpaquete(mdulo)numpyesusadoencasitodoslosclculosnumricosusandoPython.EsunpaquetequeproveeaPythondeestructurasdedatosvectoriales,matriciales,yderangomayor,dealtorendimiento.EstimplementadoenCyFortran,demodoquecuandolosclculossonvectorizados(formuladosconvectoresymatrices),elrendimientoesmuybueno.

    Parausarnumpynecesitamosimportarelmdulousando,porejemplo:

    In[187]: fromnumpyimport*

    Enelpaquetenumpylaterminologausadaparavectores,matricesyconjuntosde

    http://github.com/jrjohansson/scientific-python-lectureshttp://google.com/+GuillermoRubilarhttp://jrjohansson.github.com/http://github.com/gfrubi/clases-python-cientificohttp://dml.riken.jp/~rob/http://nbviewer.ipython.org/github/gfrubi/clases-python-cientifico/tree/masterhttp://ipython.org/notebook.htmlhttp://ipython.org/notebook.htmlhttp://nbviewer.ipython.org/github/gfrubi/clases-python-cientifico/tree/master/Lecture-2-Numpy.ipynb
  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 2/29

    Enelpaquetenumpylaterminologausadaparavectores,matricesyconjuntosdedatosdedimensinmayoresladeunarreglo.

    CreandoarreglosdenumpyExistenvariasformasparainicializarnuevosarreglosdenumpy,porejemplodesde

    ListasotuplasPythonUsandofuncionesdedicadasagenerararreglosnumpy,comoarange,linspace,etc.Leyendodatosdesdearchivos

    Desdelista

    Porejemplo,paracrearnuevosarreglosdematricesyvectoresdesdelistasPythonpodemosusarlafuncinnumpy.array.

    In[188]: #unvector:elargumentodelafuncinarrayesunalistadePythonv=array([1,2,3,4])

    v

    In[189]: #unamatriz:elargumentodelafuncinarrayesunalistaanidadadePythonM=array([[1,2],[3,4]])

    M

    LosobjetosvyMsonambosdeltipondarrayqueproveeelmdulonumpy.

    In[190]: type(v),type(M)

    LadiferenciaentrelosarreglosvyMesslosuforma.Podemosobtenerinformacindelaformadeunarreglousandolapropiedadndarray.shape

    In[191]: v.shape

    Out[188]: array([1,2,3,4])

    Out[189]: array([[1,2],[3,4]])

    Out[190]: (numpy.ndarray,numpy.ndarray)

    Out[191]: (4,)

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 3/29

    In[192]: M.shape

    Elnmerodeelementosdeunarreglopuedeobtenerseusandolapropiedadndarray.size:

    In[193]: M.size

    Equivalentemente,podemosusarlasfuncionesnumpy.shapeynumpy.size

    In[194]: shape(M)

    In[195]: size(M)

    Hastaelmomentoelarreglonumpy.ndarraylucecomounalistaPython(anidada).Entonces,porqusimplementenousarlistasparahacerclculosenlugardecrearuntiponuevodearreglo?

    Existenvariasrazones:

    LaslistasPythonsonmuygenerales.Ellaspuedencontenercualquiertipodeobjeto.Sustipossonasignadosdinmicamente.Ellasnopermitenusarfuncionesmatemticastalescomolamultiplicacindematricies,elproductoescalar,etc.ElimplementartalesfuncionesparalaslistasPythonnoseramuyeficientedebidoalaasignacindinmicadesutipo.LosarreglosNumpytienentipoestticoyhomogneo.Eltipodeelementosesdeterminadocuandosecreaelarreglo.LosarreglosNumpysoneficientesenelusodememoria.Debidoasutipoesttico,sepuedendesarrollarimplementacionesrpidasdefuncionesmatemticastalescomolamultiplicacinylasumadearreglosnumpyusandolenguajescompilados(seusanCyFortran).

    Usandolapropiedaddtype(tipodedato)deunndarray,podemosverqutipodedatocontieneunarreglo:

    In[196]: M.dtype

    Out[192]: (2,2)

    Out[193]: 4

    Out[194]: (2,2)

    Out[195]: 4

    Out[196]: dtype('int64')

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 4/29

    Seobtieneunerrorsiintentamosasignarunvalordeuntipoequivocadoaunelementodeunarreglonumpy:

    In[197]: M[0,0]="hola"

    Silodeseamos,podemosdefinirexplcitamenteeltipodedatosdeunarreglocuandolocreamos,usandoelargumentodtype:

    In[198]: M=array([[1,2],[3,4]],dtype=complex)

    M

    Algunostiposcomunesquepuedenserusadoscondtypeson:int,float,complex,bool,object,etc.

    Podemostambindefinirexplcitamenteelnmerodebitdelostiposdedatos,porejemplo:int64,int16,float64,complex64.

    Usandofuncionesquegeneranarreglos

    Enelcasodearreglosmsgrandesnoesprcticoinicializarlosdatosmanualmente,usandolistasPythonexplcitas.Ensulugar,podemosusarunadelasmuchasfuncionesennumpyquegeneranarreglosdediferentesformas.Algunosdelosmscomunesson:

    arange

    ValueErrorTraceback(mostrecentcalllast)in()>1M[0,0]="hola"

    ValueError:invalidliteralforlong()withbase10:'hola'

    Out[198]: array([[1.+0.j,2.+0.j],[3.+0.j,4.+0.j]])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 5/29

    In[199]: #creaunarregloconvaloresenunrango

    x=arange(0,10,1)#argumentos:desde,hasta,paso

    x

    In[200]: x=arange(1,1,0.1)

    x

    linspaceylogspace

    In[201]: #usandolinspace,ambospuntosfinalesSONincluidos.Formato:(desde,hasta,nmerodeelementos)linspace(0,10,25)

    In[202]: #logspacetambinincluyeelpuntofinal.Pordefectobase=10logspace(0,10,11,base=e)#produceeelevadoacadavalorenlinspace(0,10,11),e.d.[e**0,e**1,...,e**10]

    mgrid

    In[203]: x,y=mgrid[0:5,0:5]#similarameshgridenMATLAB

    Out[199]: array([0,1,2,3,4,5,6,7,8,9])

    Out[200]: array([1.00000000e+00,9.00000000e01,8.00000000e01,7.00000000e01,6.00000000e01,5.00000000e01,4.00000000e01,3.00000000e01,2.00000000e01,1.00000000e01,2.22044605e16,1.00000000e01,2.00000000e01,3.00000000e01,4.00000000e01,5.00000000e01,6.00000000e01,7.00000000e01,8.00000000e01,9.00000000e01])

    Out[201]: array([0.,0.41666667,0.83333333,1.25,1.66666667,2.08333333,2.5,2.91666667,3.33333333,3.75,4.16666667,4.58333333,5.,5.41666667,5.83333333,6.25,6.66666667,7.08333333,7.5,7.91666667,8.33333333,8.75,9.16666667,9.58333333,10.])

    Out[202]: array([1.00000000e+00,2.71828183e+00,7.38905610e+00,2.00855369e+01,5.45981500e+01,1.48413159e+02,4.03428793e+02,1.09663316e+03,2.98095799e+03,8.10308393e+03,2.20264658e+04])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 6/29

    In[204]: x

    In[205]: y

    Datosaleatorios

    In[206]: fromnumpyimportrandom

    In[207]: #nmerosaleatoriosuniformesen[0,1]random.rand(2,5)

    In[208]: #nmerosaleatorioscondistribucinestndarnormal(distribucingaussianademedia0yvarianza1).random.randn(2,5)

    diag

    In[209]: #unamatrizdiagonaldiag([1,2,3])

    Out[204]: array([[0,0,0,0,0],[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4]])

    Out[205]: array([[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]])

    Out[207]: array([[0.13726931,0.46006306,0.12751549,0.31390393,0.58854417],[0.53321985,0.89266936,0.34352726,0.28031981,0.65835111]])

    Out[208]: array([[0.32123624,0.77313846,0.61137692,1.17761426,0.85703361],[0.10858974,0.41251901,0.24668342,0.02793359,0.89666914]])

    Out[209]: array([[1,0,0],[0,2,0],[0,0,3]])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 7/29

    In[210]: #diagonaldesplazadadesdeladiagonalprincipaldiag([1,2,3],k=1)

    cerosyunos

    In[211]: zeros((3,3))

    In[212]: ones((3,3))

    Entrada/Salidadesde/hastaarchivos

    Valoresseparadosporcoma(Commaseparatedvalues,CSV)

    Unformatomuycomnparaarchivosdedatoseseldevaloresseparadosporcomas,oformatosrelacionados,comoporejemploTSV(tabseparatedvalues,valoresseparadosportabs).ParaleerdatosdesdetalesarchivosaunarregloNumpypodemosusarlafuncinnumpy.genfromtxt.Porejemplo,

    In[213]: !headstockholm_td_adj.dat#despliegalasprimeraslneasdelarchivostockholm_td_adj.dat

    Out[210]: array([[0,1,0,0],[0,0,2,0],[0,0,0,3],[0,0,0,0]])

    Out[211]: array([[0.,0.,0.],[0.,0.,0.],[0.,0.,0.]])

    Out[212]: array([[1.,1.,1.],[1.,1.,1.],[1.,1.,1.]])

    1800116.16.16.1118001215.415.415.4118001315.015.015.0118001419.319.319.3118001516.816.816.8118001611.411.411.411800177.67.67.611800187.17.17.1118001910.110.110.1118001109.59.59.51

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 8/29

    In[214]: data=genfromtxt('stockholm_td_adj.dat')#asignalosdatosdelarch

    ivoalarreglodata

    In[215]: data.shape

    In[216]: fig,ax=subplots(figsize=(14,4))ax.plot(data[:,0]+data[:,1]/12.0+data[:,2]/365,data[:,5])ax.axis('tight')ax.set_title('temperaturasenEstocolmo')ax.set_xlabel(u'ao')ax.set_ylabel(u'temperatura(C)');

    Usandonumpy.savetxtpodemosalmacenarunarregloNumpyaunarchivoenformatoCSV:

    In[217]: M=random.rand(3,3)

    M

    In[218]: savetxt("matrizaleatoria.csv",M)

    In[219]: !catmatrizaleatoria.csv

    Out[215]: (77431,7)

    Out[217]: array([[0.15533491,0.85066475,0.44820098],[0.47939811,0.72704259,0.67943401],[0.99101313,0.74961562,0.14550028]])

    1.553349093946976289e018.506647538827436517e014.482009800078388118e014.793981055007228154e017.270425893099794479e016.794340072736042568e019.910131291199101300e017.496156246195969652e011.455002822291754372e01

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 9/29

    In[220]: savetxt("matrizaleatoria.csv",M,fmt='%.5f')#fmtespecificaelformato

    !catmatrizaleatoria.csv

    ElformatodearchivonativodeNumpy

    Estilcuandosealmacenanarreglosdedatosyluegoseleennuevamenteconnumpy.Uselasfuncionesnumpy.saveynumpy.load:

    In[221]: save("matrizaleatoria.npy",M)

    !filematrizaleatoria.npy

    In[222]: load("matrizaleatoria.npy")

    MspropiedadesdelosarreglosNumpy

    In[223]: M.itemsize#losbitsdecadaelemento

    In[224]: M.nbytes#nmerodebytes

    In[225]: M.ndim#nmerodedimensiones

    Manipulandoarreglos

    Indexando

    Podemosindexarelementosenunarreglousandoparntesiscuadradosendices:

    0.155330.850660.448200.479400.727040.679430.991010.749620.14550

    matrizaleatoria.npy:data

    Out[222]: array([[0.15533491,0.85066475,0.44820098],[0.47939811,0.72704259,0.67943401],[0.99101313,0.74961562,0.14550028]])

    Out[223]: 8

    Out[224]: 72

    Out[225]: 2

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 10/29

    In[226]: #vesunvector,tieneporlotantoslounadimensin,yrequiereunndicev[0]

    In[227]: #Mesunamatriz,esdecirunarreglobidimensional,requieredosndicesM[1,1]

    SiomitimosunndicedeunaarreglomultidimensionalNumpyentregalafilacompleta(o,engeneral,alarreglodedimensinN1correspondiente)

    In[228]: M

    In[229]: M[1]

    Puedeobtenerselomismousando:enellugardeunndice:

    In[230]: M[1,:]#fila1

    In[231]: M[:,1]#columna1

    Podemosasignarnuevosvaloresaloselementosdeunarreglousandoelindexado:

    In[232]: M[0,0]=1

    In[233]: M

    Out[226]: 1

    Out[227]: 0.72704258930997945

    Out[228]: array([[0.15533491,0.85066475,0.44820098],[0.47939811,0.72704259,0.67943401],[0.99101313,0.74961562,0.14550028]])

    Out[229]: array([0.47939811,0.72704259,0.67943401])

    Out[230]: array([0.47939811,0.72704259,0.67943401])

    Out[231]: array([0.85066475,0.72704259,0.74961562])

    Out[233]: array([[1.,0.85066475,0.44820098],[0.47939811,0.72704259,0.67943401],[0.99101313,0.74961562,0.14550028]])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 11/29

    In[234]: #tambinfuncionaparafilasycolumnascompletasM[1,:]=0M[:,2]=1

    In[235]: M

    CortedendicesCorte(slicing)dendiceseselnombreparalasintaxisM[desde:hasta:paso]paraextraerunapartedeunarreglo:

    In[236]: A=array([1,2,3,4,5])A

    In[237]: A[1:3]

    Loscortesdendicessonmutables:siselesasignaunnuevovalorelarreglooriginalesmodificado:

    In[238]: A[1:3]=[2,3]

    A

    PodemosomitircualquieradelostresparmetrosenM[desde:hasta:paso]:

    In[239]: A[::]#desde,hastaypasoasumenlosvalorespordefecto

    In[240]: A[::2]#elpasoes2,desdeyhastaseasumendesdeelcomienzohastaelfindelarreglo

    Out[235]: array([[1.,0.85066475,1.],[0.,0.,1.],[0.99101313,0.74961562,1.]])

    Out[236]: array([1,2,3,4,5])

    Out[237]: array([2,3])

    Out[238]: array([1,2,3,4,5])

    Out[239]: array([1,2,3,4,5])

    Out[240]: array([1,3,5])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 12/29

    In[241]: A[:3]#primerostreselementos

    In[242]: A[3:]#elementosdesdeelndice3

    Losndicesnegativossecuentandesdeelfindelarreglo(losndicespositivosdesdeelcomienzo):

    In[243]: A=array([1,2,3,4,5])

    In[244]: A[1]#elltimoelementodelarreglo

    In[245]: A[3:]#losltimos3elementos

    Elcortedendicesfuncionaexactamentedelmismomodoparaarreglosmultidimensionales:

    In[246]: A=array([[n+m*10forninrange(5)]forminrange(5)])

    A

    In[247]: #unbloquepartedelarreglooriginalA[1:4,1:4]

    In[248]: #elementopormedioA[::2,::2]

    IndexadoFancy

    Out[241]: array([1,2,3])

    Out[242]: array([4,5])

    Out[244]: 5

    Out[245]: array([3,4,5])

    Out[246]: array([[0,1,2,3,4],[10,11,12,13,14],[20,21,22,23,24],[30,31,32,33,34],[40,41,42,43,44]])

    Out[247]: array([[11,12,13],[21,22,23],[31,32,33]])

    Out[248]: array([[0,2,4],[20,22,24],[40,42,44]])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 13/29

    IndexadoFancy

    Sellamaindexadofancycuandounaarregloounalistaesusadoenlugardeunndice:

    In[249]: indices_fila=[1,2,3]A[indices_fila]

    In[250]: indices_col=[1,2,1]#recuerdequeelndice1correspondealltimoelementoA[indices_fila,indices_col]

    Podemostambinusarmscarasdendices:SilamscaradendiceesunarregloNumpycontipodedatobooleano(bool),entoncesunelementoesseleccionado(True)ono(False)dependiendodelvalordelamscaradendiceenlaposicindecadaelemento:

    In[251]: B=array([nforninrange(5)])B

    In[252]: masc_fila=array([True,False,True,False,False])B[masc_fila]

    In[253]: #lomismomasc_fila=array([1,0,1,0,0],dtype=bool)B[masc_fila]

    Estacaractersticaesmuytilparaseleccionarenformacondicionalelementosdeunarreglo,usandoporejemplolosoperadoresdecomparacin:

    In[254]: x=arange(0,10,0.5)x

    Out[249]: array([[10,11,12,13,14],[20,21,22,23,24],[30,31,32,33,34]])

    Out[250]: array([11,22,34])

    Out[251]: array([0,1,2,3,4])

    Out[252]: array([0,2])

    Out[253]: array([0,2])

    Out[254]: array([0.,0.5,1.,1.5,2.,2.5,3.,3.5,4.,4.5,5.,5.5,6.,6.5,7.,7.5,8.,8.5,9.,9.5])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 14/29

    In[255]: masc=(5

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 15/29

    In[261]: v2=arange(3,3)v2

    In[262]: indices_fila=[1,3,5]v2[indices_fila]#indexadofancy

    In[263]: v2.take(indices_fila)

    Perolafuncintaketambinfuncionasobrelistasyotrosobjetos:

    In[264]: take([3,2,1,0,1,2],indices_fila)

    choose

    Construyeunarreglotomandoelementosdesdevariosarreglos:

    In[265]: cuales=[1,0,1,0]posibilidades=[[2,2,2,2],[5,5,5,5]]

    choose(cuales,posibilidades)

    lgebralinealElvectorizarelcdigoeslaclavepararealizarclculosnumricoseficientesusandoPython/Numpy.Estosignificaquelamayorpartedeunprogramadeberaserformuladoentrminosdeoperacionesconmatricesyvectores,comoporejemplolamultiplicacindematrices.

    Operacionesescalararreglo

    Podemosusarlosoperadoresaritmticosusualesparamultiplicar,sumar,restar,ydividirarreglospornmeros(escalares):

    Out[261]: array([3,2,1,0,1,2])

    Out[262]: array([2,0,2])

    Out[263]: array([2,0,2])

    Out[264]: array([2,0,2])

    Out[265]: array([5,2,5,2])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 16/29

    In[266]: v1=arange(0,5)

    In[267]: 2*v1

    In[268]: v1+2

    In[269]: A*2,A+2

    Operacioneselementoaelementoentrearreglos

    Cuandosumamos,sustraemos,multiplicadosydividimosdosarreglos,elcomportamientopordefectoesoperarelementoaelemento:

    In[270]: A*A#multiplicacinelementoaelemento

    In[271]: v1*v1

    Simultiplicamosarreglosconformascompatibles,obtenemosunamultiplicacinelementoaelementodecadafila:

    In[272]: A.shape,v1.shape

    Out[267]: array([0,2,4,6,8])

    Out[268]: array([2,3,4,5,6])

    Out[269]: (array([[0,2,4,6,8],[20,22,24,26,28],[40,42,44,46,48],[60,62,64,66,68],[80,82,84,86,88]]),array([[2,3,4,5,6],[12,13,14,15,16],[22,23,24,25,26],[32,33,34,35,36],[42,43,44,45,46]]))

    Out[270]: array([[0,1,4,9,16],[100,121,144,169,196],[400,441,484,529,576],[900,961,1024,1089,1156],[1600,1681,1764,1849,1936]])

    Out[271]: array([0,1,4,9,16])

    Out[272]: ((5,5),(5,))

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 17/29

    In[273]: A*v1

    lgebramatricial

    Ylamultiplicacindematrices?Podemosrealizarladedosformas.Podemosusarlafuncindot,queaplicaunamultiplicacinmatrizmatriz,matrizvectorounproductointernoentrevectoresasusdosargumentos:

    In[274]: dot(A,A)

    In[275]: dot(A,v1)

    In[276]: dot(v1,v1)

    Alternativamente,podemostransformarelarregloaltipomatrix.Estocambiaelcomportamientodelosoperadoresaritmticosestndar+,,*aldelgebradematrices.

    In[277]: M=matrix(A)v=matrix(v1).T#aplicalatraspuesta,convirtindoloenvectorcolumna

    In[278]: v

    Out[273]: array([[0,1,4,9,16],[0,11,24,39,56],[0,21,44,69,96],[0,31,64,99,136],[0,41,84,129,176]])

    Out[274]: array([[300,310,320,330,340],[1300,1360,1420,1480,1540],[2300,2410,2520,2630,2740],[3300,3460,3620,3780,3940],[4300,4510,4720,4930,5140]])

    Out[275]: array([30,130,230,330,430])

    Out[276]: 30

    Out[278]: matrix([[0],[1],[2],[3],[4]])

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 18/29

    In[279]: M*M

    In[280]: M*v

    In[281]: #productorinteriorv.T*v

    In[282]: #conobjetosmatriciales,ellgebramatricialestndaresusadav+M*v

    Siintentamossumar,restar,omultiplicarobjetosconformasincompatibles,obtendremosunerror:

    In[283]: v=matrix([1,2,3,4,5,6]).T

    In[284]: shape(M),shape(v)

    Out[279]: matrix([[300,310,320,330,340],[1300,1360,1420,1480,1540],[2300,2410,2520,2630,2740],[3300,3460,3620,3780,3940],[4300,4510,4720,4930,5140]])

    Out[280]: matrix([[30],[130],[230],[330],[430]])

    Out[281]: matrix([[30]])

    Out[282]: matrix([[30],[131],[232],[333],[434]])

    Out[284]: ((5,5),(6,1))

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 19/29

    In[285]: M*v

    Veatambinlasfuncionesrelacionadas:inner,outer,cross,kron,tensordot.Porejemplo,introduzcahelp(kron).

    Transformacionesdearreglos/matrices

    Anteshemosusado.Tparatransponerunvectorv.Podemostambinusarlafuncintransposeparaconseguirelmismoresultado.

    Otrasfuncionesmatemticasquetransformanobjetosmatricialesson:

    In[]: C=matrix([[1j,2j],[3j,4j]])C

    In[]: conjugate(C)

    Hermticoconjugado:transpuesta+conjugado

    In[]: C.H

    Podemosextraerlaspartesrealeseimaginariasdeunarregloconelementoscomplejosusandorealyimag:

    In[]: real(C)#lomismoque:C.real

    ValueErrorTraceback(mostrecentcalllast)in()>1M*v

    /usr/lib/python2.7/distpackages/numpy/matrixlib/defmatrix.pycin__mul__(self,other)328ifisinstance(other,(N.ndarray,list,tuple)):329#Thispromotes1Dvectorstorowvectors>330returnN.dot(self,asmatrix(other))331ifisscalar(other)ornothasattr(other,'__rmul__'):332returnN.dot(self,other)

    ValueError:objectsarenotaligned

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 20/29

    In[]: imag(C)#lomismoque:C.imag

    Podemostambinextraerelmduloyelargumentocomplejo

    In[]: angle(C+1)#AtencinusuariosdeMATLAB,seusaangleenlugardearg

    In[]: abs(C)

    Clculosconmatrices

    Inversa

    In[]: linalg.inv(C)#equivalenteaC.I

    In[]: C.I*C

    Determinante

    In[]: linalg.det(C)

    In[]: linalg.det(C.I)

    Clculoscondatos

    AmenudoestilalmacenardatosenarreglosNumpy.Numpyproveefuncionespararealizarclculosestadsticosdelosdatosenunarreglo.

    Porejemplo,calculemosalgunaspropiedadesdelosdatosdelatemperaturadeEstocolmoquediscutimosanteriormente.

    In[]: #recuerde,losdatosdelatemperaturaestnalmacenadosenlavariabledatashape(data)

    mean

    In[]: #latemperaturaestalmacenadaenlacolumna3mean(data[:,3])

    LatemperaturadiariapromedioenEstocolmoenlosltimos200aoshasidoaproximadamente6.2C.

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 21/29

    aproximadamente6.2C.

    Desviacinestndaryvarianza

    In[]: std(data[:,3]),var(data[:,3])

    minandmax

    In[]: #valormnimodelpromediodiariodetemperatura.Lomismoquemin(data[:,3])data[:,3].min()

    In[]: #valormximodelpromediodiariodetemperatura.Lomismoquemax(data[:,3])data[:,3].max()

    sum,prod,andtrace

    In[]: d=1+arange(0,10)d

    In[]: #sumatodosloselementossum(d)

    In[]: #multiplicatodosloselementosprod(d)

    In[]: #sumaacumulativacumsum(d)

    In[]: #productoacumulativocumprod(d)

    In[]: #lomismoque:diag(A).sum()trace(A)

    Clculosconsubconjuntosdeunarreglo

    Podemoscalcularusandosubconjuntosdelosdatosdeunarreglousandoelindexado,indexadofancy,ylosotrosmtodosparaextraerdatosdesdeunarreglo(descritomsarriba).

    Porejemplo,consideremosnuevamentelosdatosdetemperaturadeEstocolmo:

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 22/29

    In[]: !headn3stockholm_td_adj.dat

    Elformatodelosdatoses:ao,mes,da,temperaturapromediodiaria,mnima,mxima,lugar.

    Siestamosinteresadossloenlatemperaturapromediodeunmesparticular,Febreroporejemplo,podemoscrearunamscaradendiceyseleccionarslolosdatosdeesemesusando:

    In[]: unique(data[:,1])#lacolumnamesasumevaloresentre1y12

    In[]: masc_feb=(data[:,1]==2)#losparntesis()sonopcionales

    In[]: #losdatosdetemperaturaestnenlacolumna3mean(data[masc_feb,3])

    Estasfuncionesponenanuestradisposicinherramientasmuypoderosasparaprocesardatos.Porejemplo,paraextraerlastemperaturaspromediomensualesparacadamesdelaoslonecesitamosunaspocaslneasdecdigo:

    In[]: meses=arange(1,13)media_mensual=[mean(data[data[:,1]==mes,3])formesinmeses]

    fig,ax=subplots()ax.bar(meses,media_mensual)ax.set_xlabel("Mes")ax.set_ylabel("Temperaturapromediomensual");

    Clculoscondatosmultidimensionales

    Cuandoseaplicanfuncionescomomin,max,etc.,aarreglosmultidimensionales,avecessedeseaaplicarlasalarreglocompleto,yenotrasocasionessloporfilasocolumnas.Podemosespecificarcmosecomportanestasfuncionesusandoelargumentoaxis(eje):

    In[]: m=random.rand(3,3)m

    In[]: #mximoglobalm.max()

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 23/29

    In[]: #mximoencadacolumnam.max(axis=0)

    In[]: #mximoencadafilam.max(axis=1)

    Muchasotrasfuncionesymtodosdelasclasesarrayymatrixaceptanelargumento(optional)axis.

    Cambiandolaforma,redimensionandoyapilandoarreglosLaformadeunarregloNumpypuedesermodificadasincopiarlasdatosinvolucrados,loquehacequeestaoperacinsearpida,incluyoconarreglosgrandes.

    In[]: A

    In[]: n,m=A.shape

    In[]: B=A.reshape((1,n*m))B

    In[]: B[0,0:5]=5#modificaelarreglo

    B

    In[]: A#lavariableoriginalestambincambiada.Bsloconstituyeunaformadistintadeverlosmismosdatos

    Podemostambinusarlafuncinflattenparatransformarunarreglomultidimensionalaunvector.Adiferenciadereshapeestafuncincreaunacopiadelosdatos.

    In[]: B=A.flatten()

    B

    In[]: B[0:5]=10

    B

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 24/29

    In[]: A#ahoraAnohacambiado,yaquelosdatosdeBhansidoduplicadosdesdeA

    Agregandounadimensinadicional:newaxis

    Connewaxis,podemosinsertarunanuevadimensionenunarreglo,porejemplo,paraconvertirunvectorenlafilaocolumnadeunamatriz:

    In[]: v=array([1,2,3])

    In[]: shape(v)

    In[]: #creaunamatrizconelvectorvcomosucolumnav[:,newaxis]

    In[]: #matrizcolumnav[:,newaxis].shape

    In[]: #matrizfilav[newaxis,:]

    In[]: v[newaxis,:].shape

    Apilandoyrepitiendoarreglos

    Podemoscrearvectoresymatricesmsgrandesapartirdeotrasmspequeasusandolasfuncionesnrepeat(repetir),tile(teselar,"embaldosar"),vstack(apilarverticalmente),hstack(apilarhorizontalmente),yconcatenate(concatenar):

    tileyrepeat

    In[]: a=array([[1,2],[3,4]])

    In[]: #repitecadaelemente3vecesrepeat(a,3)

    In[]: #repitelamatriz3vecestile(a,3)

    concatenate

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 25/29

    In[]: b=array([[5,6]])

    In[]: concatenate((a,b),axis=0)

    In[]: concatenate((a,b.T),axis=1)

    hstackandvstack

    In[]: vstack((a,b))

    In[]: hstack((a,b.T))

    Copyy"deepcopy"Paraalcarzarunaltodesemo,lasasignacionesenPythonusualmentenocopianlosobjetosinvolucrados.Estoesimportantecuandosepasanobjetosafunciones,paraasevitarusoexcesivodememoriacopiandocuandonoesnecesario(trminotcnico:pasoporreferencia)

    In[]: A=array([[1,2],[3,4]])

    A

    In[]: #ahoraBapuntaalmismoarregloqueAB=A

    In[]: #cambiarBafectaaAB[0,0]=10

    B

    In[]: A

    Siqueremosevitarestecomportamiento,paraasobtenerunnuevoobjectoBcopiadodesdeA,perototalmenteindependientedeA,necesitamosrealizaruna"copiaprodunfa"("deepcopy")usandolafuncincopy:

    In[]: B=copy(A)

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 26/29

    In[]: #ahoraAnocambiasimodificamosBB[0,0]=5

    B

    In[]: A

    IterandosobreelementosdeunarregloGeneralmente,deseamosevitariterarsobreloselementosdeunarreglodondeseaposible(acualquierprecio!).LaraznesqueenunlenguajeinterpretadocomoPython(oMATLAB),lasiteracionessonrealmentelentascomparadasconlasoperacionesvectorizadas.

    Sinembargo,algunasvecesesineludible.EntalescaseselbuclePythonforeslaformamsconvenienteparaiterarsobreunarreglo:

    In[]: v=array([1,2,3,4])

    forelementoinv:printelemento

    In[]: M=array([[1,2],[3,4]])

    forfilainM:print"fila",filaforelementoinfila:printelemento

    Cuandonecesitamositerarsobrecadaelementodeunarregloymodificarsuselementos,esconveniendousarlafuncinenumerateparaobtenertantoelelementocomosundiceenelbuclefor:

    In[]: forind_fila,filainenumerate(M):print"ind_fila",ind_fila,"fila",filaforind_colu,elementoinenumerate(fila):print"ind_colu",ind_colu,"elemento",elemento#actualizalamatriz:elevaalcuadradocadaelementoM[ind_fila,ind_colu]=elemento**2

    In[]: #cadaelementoenMestahoraalcuadradoM

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 27/29

    VectorizandofuncionesComosehamencionadoenvariasocasiones,paraobtenerunbuenrendimientodeberamostratardeevitarrealizarbuclessobreloselementosdenuestrosvectoresymatrices,yensulugarusaralgoritmosvectorizados.Elprimerpasoparaconvertirunalgoritmoescalaraunovectorizadoesasegurarnosquelasfuncionesqueescribamosfuncionenconargumentosvectoriales.

    In[]: defTheta(x):"""implementacinescalardelafuncinescalndeHeaviside."""ifx>=0:return1else:return0

    In[]: Theta(array([3,2,1,0,1,2,3]))

    Ok,esonofuncionporquenodefinimoslafuncinThetademodoquepuedamanejarargumentosvectoriales...

    ParaobtenerunaversionvectorizadadeThetapodemosusarlafuncinvectorizedeNumpy.Enmuchoscasos,puedevectorizarautomticamenteunafuncin:

    In[]: Theta_vec=vectorize(Theta)

    In[]: Theta_vec(array([3,2,1,0,1,2,3]))

    Podemostambinimplementarlafuncindemodoquedesdeelcomienzoacepteunargumentovectorial(estorequieremsesfuerzo,peromejorarelrendimiento):

    In[]: defTheta(x):"""ImplementacinpreparadaparavectoresdelafuncinescalndeHeaviside."""return1*(x>=0)

    In[]: Theta(array([3,2,1,0,1,2,3]))

    In[]: #ytambinfuncionaparaescalares!Theta(1.2),Theta(2.6)

  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 28/29

    UsandoarreglosensentenciascondicionalesCuandoseusanarreglosensentenciascondicionales,porejemploensentenciasifyotrasexpresionesbooleanas,necesitamosusaranyobienall,querequierequetodosloselementosdeunarregloseevalenconTrue:

    In[]: M

    In[]: if(M>5).any():print"almenosunelementodeMesmayorque5"else:print"ningnelementodeMesmayorque5"

    In[]: if(M>5).all():print"todosloselementosdeMsonmayoresque5"else:print"notodosloselementosdeMsonmayoresque5"

    ConversindetipoComolosarreglosdeNumpysondetipoesttico,eltipodeunarrglonopuedesercambiadoluegodequeescreado.Sinembarg,podemosconvertirexplcitamenteunarreglodeuntipoaotrousandolasfuncionesastype(vertambinlasfuncionessimilaresasarray).Estocreaunnuevoarreglodeunnuevotipo:

    In[]: M.dtype

    In[]: M2=M.astype(float)

    M2

    In[]: M2.dtype

    In[]: M3=M.astype(bool)

    M3

    LecturaadicionalNumpy(http://numpy.scipy.org)http://scipy.org/Tentative_NumPy_Tutorial(http://scipy.org/Tentative_NumPy_Tutorial)http://scipy.org/NumPy_for_Matlab_Users

    http://scipy.org/NumPy_for_Matlab_Usershttp://numpy.scipy.org/http://scipy.org/Tentative_NumPy_Tutorial
  • 1/4/2015 nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb

    http://nbviewer.ipython.org/github/gfrubi/clasespythoncientifico/blob/master/Lecture2Numpy.ipynb 29/29

    (http://scipy.org/NumPy_for_Matlab_Users)UnaguadeNumpyparausuariodeMATLAB.

    http://scipy.org/NumPy_for_Matlab_Users