02 Intro Python
02 Intro Python
Cecilia Jarne
https://www.python.org
Cecilia Jarne Fundamentos de Python [email protected] 2 / 67
Motivos para aprender Python
Fácil de aprender.
Un conjunto gigante de librerı́as.
Soporte cientı́fico excelente!!
Se puede desarrollar software bastante rápido.
Posee una licencia de código abierto.
Una comunidad gigante desarrollando con la cual realmente se puede
contar.
1 x = 1
2 x = "text" # dynamic typing :)
https://docs.python.org/2/library/types.html
https://docs.python.org/2/library/types.html
1 if(a>b):
2 foo()
3 bar()
4 baz()
1 def function(x,y,z):
2 x=3*y
3 return x+y-z
1 int factorial(int x)
2 {
3 if (x == 0)
4 return 1;
5 else
6 return x * factorial(x - 1);
7 }
En python es obligatoria:
1 def factorial(x):
2 if x == 0:
3 return 1
4 else:
5 return x * factorial(x - 1)
Un ejemplo simple:
1
2 def jugar(intento=1):
3 respuesta = raw_input("De que color es una naranja? ")
4 if respuesta != "naranja":
5 if intento < 3:
6 print "\nFallaste Intentalo de nuevo"
7 intento += 1
8 jugar(intento) # Llamada recursiva
9 else:
10 print "\nPerdiste"
11 else:
12 print "\nGanaste!"
13 jugar()
Matemáticos:
Name Function symbol
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and returns remainder b% a = 0
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
Booleanos:
Operation Result
x or y if x is false, then y, else x
x and y if x is false, then x, else y
not x if x is false, then True, else False
1 a= "Soy Cecilia"
2 b= ’Soy de Argentina’
Un ejemplo:
1 a=[1,’apple’,1.2]
Tuple
1 a=(1,’apple’,1.2)
Dict
1 a={’name’:’Giovanni’, ’age’:42}
Set
1 a={1,’apple’,1.2}
1 a[-1]
list.append(obj)
Appends object obj to list
list.count(obj)
Returns count of how many times obj occurs in list
list.extend(seq)
Appends the contents of seq to list
list.index(obj)
Returns the lowest index in list that obj appears
list.insert(index, obj)
list.pop(obj=list[-1])
Removes and returns last object or obj from list
list.remove(obj)
Removes object obj from list
list.reverse()
Estas librerı́as:
NumPy:
http://www.numpy.org/
SciPy:
http://www.scipy.org/
MatPlotLib:
http://matplotlib.org/
• Clustering.
• Fourier transforms.
• numerical integration, interpolations.
• data I/O, LAPACK.
• sparse matrices, linear solvers, optimization.
• signal processing.
• statistical functions.
Cecilia Jarne Fundamentos de Python [email protected] 26 / 67
Matplotlib
Python scripts.
The Python y tambien IPython shell.
The jupyter notebook.
Web application servers.
Graphical user interface toolkits.
1 import numpy
2 import scipy
3 import matplotlib.pyplot
1 import numpy
2 import numpy as np
3 from numpy import *
Yo uso:
1 import numpy as np
2 import scipy as sp
3 import matplotlib.pyplot as pp (o tambien) plt
Funcionalidad de NumPy :
Funciones polinómicas.
Cómputo estadı́stico.
Generadores de números aleatoreos.
Transformada de Fourier discreta.
Cambio de tamaño, forma, testeo y cálculo con arrays.
1 import numpy as np
2 >>> x = np.array([2, 3, 1, 0])
3 >>> print(x)
4 [2 3 1 0]
5
6 >>> np.arange(10)
7 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
8
9 >>> np.arange(2, 10, dtype=np.float)
10 array([ 2., 3., 4., 5., 6., 7., 8., 9.])
11
12 >>> np.arange(2, 3, 0.1)
13 array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
14
15 >>> np.linspace(1., 4., 6)
16 array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ])
reshape:
1 >>> x = np.array([1.,2.,3.,4.])
2 >>> x
3 array([ 1., 2., 3., 4.])
4 >>> x.T
5 array([ 1., 2., 3., 4.])
1 x = np.array([[1,2],[3,4]], dtype=np.float64)
2 y = np.array([[5,6],[7,8]], dtype=np.float64)
3
4 # Elementwise sum; both produce the array
5
6 >>>print(x + y)
7 >>>print(np.add(x, y))
8 [[ 6.0 8.0]
9 [10.0 12.0]]
10
11 # Elementwise difference; both produce the array
12
13 >>>print(x - y)
14 >>>print(np.subtract(x, y))
15 [[-4.0 -4.0]
16 [-4.0 -4.0]]
1 import numpy as np
2
3 file_name_you_want = np.loadtxt(fname,delimiter=" ")
4
5 print "First column element: ",file_name_you_want[0]
6 #to get the full column:
7
8 Transpose_your_file = file_name_you_want.T
9
10 print "First column: ", Transpose_your_file[0]
1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()
1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()
1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()
1 import numpy as np
2 import matplotlib.pyplot as pp
3 from scipy.optimize import curve_fit
4
5 def fitFunc(t, a, b, c):
6 return a*np.exp(-b*t) + c
7
8 t = np.linspace(0,4,50)
9 temp = fitFunc(t, 2.5, 1.3, 0.5)
10 noisy = temp + 0.25*np.random.normal(size=len(temp))
11 fitParams, fitCovariances = curve_fit(fitFunc, t, noisy)
12
13 pp.figure(figsize=(12, 6))
14 pp.ylabel(’Temperature (C)’, fontsize = 16)
15 pp.xlabel(’time (s)’, fontsize = 16)
16 pp.xlim(0,4.1)
17 pp.errorbar(t, noisy, fmt = ’ro’, yerr = 0.2)
18 sigma = [fitCovariances[0,0], fitCovariances[1,1], fitCovariances[2,2] ]
19 pp.plot(t, fitFunc(t, fitParams[0], fitParams[1], fitParams[2]))
20 pp.plot(t, fitFunc(t, fitParams[0] + sigma[0], fitParams[1] - sigma[1], fitParams[2] + sigma[2]))
21 pp.plot(t, fitFunc(t, fitParams[0] - sigma[0], fitParams[1] + sigma[1], fitParams[2] - sigma[2]))
22 pp.savefig(’dataFitted.pdf’, bbox_inches=0, dpi=600)
23 pp.show()
1 import networkx as nx
2 import pygraphviz
3 from graphviz import *
1 import matplotlib.pyplot as pp
2 pp.hist([vector,bins=bins)
1 import matplotlib.pyplot as pp
2 pp.specgram(signal, NFFT=nfft, Fs= sample_rate, noverlap=par, cmap=’jet’
)
Scikit learn:
http://scikit-learn.org
Pandas
http://pandas.pydata.org/
Invitación: http://www.python.org.ar/wiki/PyCamp/2018