Download presentación de las principales bibliotecas en Python - ESMG-MX

Document related concepts
no text concepts found
Transcript
7/7/2016
Seminario_Python
In [17]: from IPython.display import Image
Image(filename='ESMG.png')
Out[17]:
Por: Javier A. Estrada Santos y Carlos A. Romano
Pérez
Python
Python (80's, Guido van Rossum) es un lenguage de programación:
Interpretado
Interactivo
Orientado a objetos
Incorpora modulos, excepciones,escritura dinámica, estructuras dinámicas de alto nivel y clases.
Python combina gran poder con una sintáxis clara (similiar a pseudocódigo) y es portable para cualquier SO
además de ser multiparadigma.
La fundación de Software Python es una organización independiente sin fines de lucro.
Tipo de números por defecto:
Enteros (int): 1, 2, 3
Flotantes (float): 0.1, 3.141592 (64­bit)
Complejos: 0+1j, 1.1+3.5j
Booleanos: True, False
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
1/8
7/7/2016
Seminario_Python
Almacenamiento de datos
Strings (str): ”python”, ”foo”
Listas (list): [1, 2, 3], [0.5, ”bar”, True], [[0, 1, 0], [1, 0, 0]]
Tuplas (tuple): (1, 2, 3)
Diccionarios (dict): {”key0”: 1.5, ”key1”: 3.0}
Sintáxis
C++
include
using namespace std;
int main()
{
cout<<"Hello World";
return 0;
}
Java
public class Main{ public static void main(String[] args) { System.out.println("Hello World"); } }
Python 3.x
print ('Hola Mundo')
Ventajas
No requiere definir el tipo de variable previamente
No se requiere tener conocimientos de manejo de memoria
Fácil lectura del código
Iteradores, generadores
Gran comunidad web
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
2/8
7/7/2016
Seminario_Python
Python2 o Python3?
Python3 fue lanzado en 2008 (la primera versión no retrocompatible) y ofrece varias mejoras sobre P2.x
mientras que la versión final de P2, la 2.7 fue liberada a mediados del 2010.
P3 se encuentra siendo desarrollado activamente.
La desventaja de esto es que mucho software de calidad aún no funciona en P3, siendo P2.x la versión más
utilizada.
Librerías:
Scipy
Scipy (Scientific Python) es una 'ecosistema' de librerías gratuitas para realizar cálculo científico. Este se
encuentra conformada por los siguientes integrantes:
Scipy library
IPython
Numpy
Sympy
Matplotlib
Pandas
Jupyter
El IPython Notebook (jupyter) es un IDE (Interactive Development Environment) en una aplicación web que
permite crear y compartir documentos que contengan código, ecuaciones, gráficas y texto. Soporta la mayoría
de los lenguajes de programación e incluye librerías de 'widgets' para interactuar con el código.
http://jupyter.org/ (http://jupyter.org/)
También es compatible con la notación de Latex:
i
∫
Ω
n
(ϕSf + (1 − ϕ)cr ) wd x + Δtn ∫
−
Ω
− Δtn ∫
wg
∂
∂N Ω
∫
n
i
n
∇w ⋅ (Sf ϕ D
−
−
−
−
(n)
d x + Δt ∫
−
i
(
c
f
n
(n−1)
i
f
i
f
Ω
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
n
)
∂t
i
c )wd x
f
−
wd x =
−
)
∂ (1 − ϕ)
+ Δt [−cr (
n
− u
−
n
∂t
Ω
{(ϕSf + (1 − ϕ)cr ) c
∂ ϕSf
i
⋅ ∇c
i
n
f
i/p
+ (g )
]} wd x
−
3/8
7/7/2016
Seminario_Python
Widgets:
In [17]: import sys
print (sys.version)
3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Dec 7 2015, 11:16:01)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
In [3]: import numpy as np
import bqplot.pyplot as plt
size = 100
plt.figure(title='Gráfico de dispersión')
plt.scatter(np.random.randn(size), np.random.randn(size), color=np.ra
ndom.randn(size))
plt.show()
In [1]: from pythreejs import *
f = """
function f(origu,origv) {
// scale u and v to the ranges I want: [0, 2*pi]
var u = 2*Math.PI*origu;
var v = 2*Math.PI*origv;
var x = Math.sin(u);
var y = Math.cos(v);
var z = Math.cos(u+v);
return new THREE.Vector3(x,y,z)
}
"""
surf_g = ParametricGeometry(func=f);
surf = Mesh(geometry=surf_g, material=LambertMaterial(color='green',
side='FrontSide'))
surf2 = Mesh(geometry=surf_g,
material=LambertMaterial(color='yellow', side='BackSide'))
scene = Scene(children=[surf, surf2, AmbientLight(color='#777777')])
c = PerspectiveCamera(position=[5, 5, 3], up=[0, 0, 1],
children=[DirectionalLight(color='white',
position=[3, 5, 1],
intensity=0.6)])
Renderer(camera=c, scene=scene, controls=
[OrbitControls(controlling=c)])
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
4/8
7/7/2016
Seminario_Python
Sympy
Sympy es una librería para realizar matemáticas simbólicas donde el interés no es en valor numérico, si
no en la expresión.
In [22]: from sympy import *
In [23]: sqrt(8)
Out[23]: 2*sqrt(2)
In [24]: init_printing(use_latex='mathjax')
In [25]: sqrt(8)
Out[25]:
2√2
Con simpy se pueden generar símbolos para trabajar con ellos:
In [27]: a=symbols('a')
expresion=a/2+1
expresion
Out[27]:
a
+ 1
2
Al tener definida una expresión se pueden realizar operaciones:
In [29]: expresion+a+2
Out[29]:
3a
+ 3
2
Se pueden simplicar expresiones:
In [30]: x=symbols('x')
expr=sin(x)**2+cos(x)**2
expr
Out[30]:
sin
2
(x) + cos
2
(x)
In [31]: simplify(expr)
Out[31]:
1
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
5/8
7/7/2016
Seminario_Python
Derivadas
In [32]: x,t,z=symbols('x t z')
expr=sin(x)*exp(x)
expr
Out[32]:
e
x
sin (x)
In [33]: expr1=diff(expr, x)
expr1
Out[33]:
e
x
sin (x) + e
x
cos (x)
In [35]: integrate(expr1,(x))
Out[35]:
e
x
sin (x)
Solución de ecuaciones
In [36]: expr=x**2-2
expr
Out[36]:
x
2
− 2
In [37]: solve(expr,x)
Out[37]:
[−√2 ,
√2 ]
Ecuaciones diferenciales
In [39]: y=Function('y')
expr=Eq(y(t).diff(t, t) - y(t), exp(t))
expr
Out[39]:
d
2
−y(t) +
2
y(t) = e
t
dt
In [40]: dsolve(expr,y(t))
Out[40]:
y(t) = C2 e
−t
t
+ (C1 +
)e
t
2
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
6/8
7/7/2016
Seminario_Python
Pandas
Pandas es una librería de alto rendimiento que provee estructuras y análisis de datos.
In [41]: import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
tabla=pd.read_excel("Seminarios.xlsx")
tabla
Out[41]:
Tema
Ponente
Lugar Ano Mes
Duracion
0 Programacion
Javier
Sala 1 2016 Julio
150
1 Programacion
Carlos
Sala 1 2016 Julio
150
2 Visualizacion
Edgar
Sala 4 2016 Junio 120
3 Geoestadistica Martin
Sala 1 2016 Junio 125
4 Geoestadistica Francisco Sala 5 2016 Marzo 75
In [42]: tabla['Mes'].value_counts()
2
Out[42]: Julio
Junio
2
Marzo
1
Name: Mes, dtype: int64
In [43]: tema=tabla['Tema'].value_counts()
tema.plot(kind='bar')
plt.show
Out[43]: <function matplotlib.pyplot.show>
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
7/8
7/7/2016
Seminario_Python
In [44]: sala=tabla['Lugar'].value_counts()
sala.plot(kind='pie',figsize=(4,4))
plt.show
Out[44]: <function matplotlib.pyplot.show>
In [45]: pd.pivot_table(tabla,values='Duracion',index=['Lugar'],columns=
['Ano'])
Out[45]: Ano
2016
Lugar
Sala 1 141.666667
Sala 4 120.000000
Sala 5 75.000000
http://localhost:8888/nbconvert/html/Seminario_Python.ipynb?download=false
8/8