Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
robertopucp
GitHub Repository: robertopucp/1eco35_2022_2
Path: blob/main/Lab1/Python_Lab_1.ipynb
2714 views
Kernel: Python 3 (ipykernel)

Laboratorio 1 Python

1.0 Types of variables

a1 = 3.141 a1 = 3.141 a1 = 3.141 a1 = 3.141 a1 = 3.141 a1 = 3.141 a1 = 3.141 a1 = 3.141 a1 = 3.141 type(a1) ## Ctrl + Enter
float
# Añadir nueva liena de codigo botón: B # Borrar linea de codigo con: DD # recuperar : Z # pasar de código a comentario : Ctrl + / # unir celdas de código : Shift + M # dividir celdas de código : Ctrl + Shit + - # seleccionar varias lineas de codigo Shift + tecla hacia abajo o arriba
# from float to int c = int(a1) type(c)
int
b1 = 10000 type(b1) # from int to float float(b1) b2 = 8 type(b2)
int
c1 = "My first python code" # "My first python code" usando doble comilla print(c1) # show that varaible's content type(c1) # providing varaibles's type
My first python code
str
# including a space using \n c1 = "First python code" c2 = "at R y python Class" print(c1,'\n',c2)
First python code at R y python Class
# join string print(c1 + " : " + c2)
First python code : at R y python Class
# f-string print(f'{c1} : semester 2022-1')
First python code : semester 2022-1
d = 2022
print(f'{c1} : semester {d}-1')
First python code : semester 2022-1
print('{} : semester {}-1'.format(c1,d))
First python code : semester 2022-1
# Substr elements from string c1[0:5]
'First'
#first character print('Fisrt letter is :',c1[0])
Fisrt letter is : F
#first word print('Fisrt word is :',c1[0:5])
Fisrt word is : First

1.2 Boolean

It’s used to represent the truth value of an expression.

"a" == "a"
True
1 > 1
False
z1 = (1==1) z1
True
int(z1) # true is 1 in numerical system
1
z2 = (10 > 20) int(z2) # false is 0 in numerical system
0

1.3 Tuple

It is an ordered and immutable Python object

T1 = (1,4,8,10,20,15,4,5,3,8) type(T1)
tuple
# aritmethic operations print('Suma:', sum(T1),"\n", "Minimo:", min(T1), '\n', "Maximo:", max(T1))
Suma: 78 Minimo: 1 Maximo: 20
len(T1) # lenght of tuple
10

Indexing Tuple

T1 = (1,4,8,10,20,15,4,5,3,8) #### 0,1,2, 3, 4 T1[0]
4
T1[0:5] # desde la posición 0 hasta el 4
(1, 4, 8, 10, 20)
T1[1] # get tuple's element
4
T1[0:3]
(1, 4, 8)
# It is not possible to change T1[0] = 4
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [33], in <cell line: 2>() 1 # It is not possible to change ----> 2 T1[0] = 4 TypeError: 'tuple' object does not support item assignment
T1 = (1,4,8,10,20,15,4,5,3,8) # -3,-2,-1 T1[-3:-1]
(5, 3)
#position T1.index(8)
2

1.4 List

It is an ordered and mutable Python container.

L1 = [] print(L1) type(L1)
[]
list
dis1 = [ "ATE", 'BARRANCO','BREÑA', 'CALLAO', 'CARABAYLLO' ] dis1
['ATE', 'BARRANCO', 'BREÑA', 'CALLAO', 'CARABAYLLO']
dis2 = ['ATE', 'BARRANCO','BREÑA', 'CALLAO', 'CARABAYLLO','CHACLACAYO','CHORRILLOS','CIENEGUILLA' ,'COMAS','EL_AGUSTINO','INDEPENDENCIA']
len(dis2) # numero de elementos
11
dis2[0] = "CALLAO" print(dis2)
['CALLAO', 'BARRANCO', 'BREÑA', 'CALLAO', 'CARABAYLLO', 'CHACLACAYO', 'CHORRILLOS', 'CIENEGUILLA', 'COMAS', 'EL_AGUSTINO', 'INDEPENDENCIA']
# Idenxing print(dis2[1])
BARRANCO
dis2[2:5] # (5-1=4)
['BREÑA', 'CALLAO', 'CARABAYLLO']
dis2[3:7]
['CALLAO', 'CARABAYLLO', 'CHACLACAYO', 'CHORRILLOS']
dis2[-5:-1]
['CHORRILLOS', 'CIENEGUILLA', 'COMAS', 'EL_AGUSTINO']
num = [13,5,5,8,9,10,5,8,13,1,20] num.sort() print(num)
[1, 5, 5, 5, 8, 8, 9, 10, 13, 13, 20]
# append new elements num.append(102)
# append new list num2 = [10,20,30] num.extend(num2) print(num)
[1, 5, 5, 5, 8, 8, 9, 10, 13, 13, 20, 102, 10, 20, 30]
print(num.index(102))
11
print("Suma:", sum(num),'\n', "Minimo:", min(num), '\n', "Maximo:", max(num))
Suma: 259 Minimo: 1 Maximo: 102
Postal_code = { 'Majes': 40520 , 'Mollendo': 40701, 'Islay': 40704, 'Cotahuasi': 40801, 'Alca': 40802 } type(Postal_code) # dict de diccionario # 'Majes', 'Mollendo' son llaves
dict
Postal_code
{'Majes': 40520, 'Mollendo': 40701, 'Islay': 40704, 'Cotahuasi': 40801, 'Alca': 40802}
Postal_code.keys()
dict_keys(['Majes', 'Mollendo', 'Islay', 'Cotahuasi', 'Alca'])
# Get information from key Postal_code['Alca']
40802
# Get information from key Postal_code.get('Alca')
40802
# Drop key Postal_code.pop('Islay') Postal_code
{'Majes': 40520, 'Mollendo': 40701, 'Cotahuasi': 40801, 'Alca': 40802}
# add new elements Postal_code.update( { "CHARCANA" : [1,2] } ) #diccioanrio dentro de otro diccionario Postal_code.update( {"LOMAS": {"UBIGEO": 40311, "Poverty Rate" : "18.2%", "Population" : "20 mil"}})
Postal_code
{'Majes': 40520, 'Mollendo': 40701, 'Islay': 40704, 'Cotahuasi': 40801, 'Alca': 40802, 'CHARCANA': [1, 2], 'LOMAS': {'UBIGEO': 40311, 'Poverty Rate': '18.2%', 'Population': '20 mil'}}
Postal_code.get('LOMAS').get('Poverty Rate')
'18.2%'
Postal_code['LOMAS']['Poverty Rate'] # forna mas usada
'18.2%'
Postal_code['LOMAS'] ['Poverty Rate']
'18.2%'
# keys cities = ['Fray Martin','Santa Rosa de Puquio','Cuchicorral','Santiago de Punchauca','La Cruz (11 Amigos)','Cerro Cañon','Cabaña Suche','San Lorenzo','Jose Carlos Mariategui','Pascal','La Esperanza','Fundo Pancha Paula','Olfa','Rio Seco','Paraiso','El Rosario','Cerro Puquio','La Campana','Las Animas','Vetancio','Roma Alta','San Jose','San Pedro de Carabayllo','Huacoy','Fundo Pampa Libre','Ex Fundo Santa Ines','Reposo','Carmelito','Santa Elena','Don Luis','Santa Ines Parcela','Asociacion Santa Ines','Roma Baja','Residencial Santa Lucia','San Francisco','Santa Margarita - Molinos','Sipan Peru','Fundo Cuadros','Bello Horizonte','El Hueco','Ex Fundo Mariategui','Naranjito','Vista Hermosa','El Sabroso de Jose Carlos Mariategui','Granja Carabayllo','Agropecuario Valle el Chillon','Camino Real','Copacabana','El Trebol','Tablada la Virgen','San Fernando de Carabayllo','San Fernando de Copacabana','La Manzana','Chacra Grande','Torres de Copacabana','San Pedro de Carabayllo','San Lorenzo','Chaclacayo','Chorrillos','Cieneguilla','Lindero','Pichicato','San Isidro','San Vicente','Piedra Liza','Santa Rosa de Chontay (Chontay)','La Libertad','El Agustino','Independencia','Jesus Maria','La Molina','La Victoria','Lince','Las Palmeras','Chosica','Lurin','Los Almacigos','Rinconada del Puruhuay','Fundo Santa Genoveva','Los Maderos','Casco Viejo','Vista Alegre','Buena Vista Alta','Lomas Pucara','Fundo la Querencia','Magdalena del Mar','Pueblo Libre','Miraflores','Pachacamac','Puente Manchay','Tambo Inga','Pampa Flores','Manchay Alto Lote B','Invasion Cementerio','Manchay Bajo','Santa Rosa de Mal Paso','Cardal','Jatosisa','Tomina','Pucusana','Honda','Quipa','Los Pelicanos','Playa Puerto Bello','Ñaves','Granja Santa Elena','Alvatroz II','Poseidon - Lobo Varado','Playa Minka Mar','Playa Acantilado','Puente Piedra','Punta Hermosa','Capilla Lucumo','Cucuya','Pampapacta','Avicola San Cirilo de Loma Negra - 03','Avicola San Cirilo de Loma Negra - 02','Avicola San Cirilo de Loma Negra - 01','Pampa Mamay','Cerro Botija','Agricultores y Ganaderos','Pampa Malanche Avicola Puma','Punta Negra','Chancheria','Rimac','San Bartolo','Plantel 41','Granja 4','Granja 5','Granja 07','Granja 44','Granja 47','Santa Maria I','Las Torres Santa Fe','San Francisco de Borja','San Isidro','San Juan de Lurigancho','Ciudad de Dios','San Luis','Barrio Obrero Industrial','San Miguel','Santa Anita - los Ficus','Santa Maria del Mar','Don Bruno','Santa Rosa','Santiago de Surco','Surquillo','Villa el Salvador','Villa Maria del Triunfo', 'Pueblo libre'] # values postal_code1 = [15001,15003,15004,15006,15018,15019,15046,15072,15079,15081,15082,15083,15088,15123,15004,15011,15012,15019,15022,15023,15026,15476,15479,15483,15487,15491,15494,15498,15047,15049,15063,15082,15083,15121,15122,15313,15316,15318,15319,15320,15321,15324,15320,15320,15320,15320,15320,15320,15121,15320,15320,15121,15320,15320,15121,15121,15122,15122,15121,15121,15121,15320,15320,15320,15320,15320,15320,15121,15121,15121,15320,15121,15319,15121,15121,15121,15320,15320,15121,15121,15121,15121,15320,15320,15320,15122,15122,15122,15122,15122,15122,15122,15122,15121,15121,15122,15122,15121,15121,15122,15122,15121,15122,15122,15122,15472,15476,15054,15056,15057,15058,15063,15064,15066,15067,15593,15594,15593,15593,15593,15593,15593,15593,15593,15311,15312,15313,15314,15316,15324,15326,15327,15328,15332,15003,15004,15006,15007,15008,15009,15011,15018,15022,15311,15328,15331,15332,15333,15046, 15001]
# Return a dictionarie ct_pc = dict( zip( cities , postal_code1) )
ct_pc
{'Fray Martin': 15001, 'Santa Rosa de Puquio': 15003, 'Cuchicorral': 15004, 'Santiago de Punchauca': 15006, 'La Cruz (11 Amigos)': 15018, 'Cerro Cañon': 15019, 'Cabaña Suche': 15046, 'San Lorenzo': 15122, 'Jose Carlos Mariategui': 15079, 'Pascal': 15081, 'La Esperanza': 15082, 'Fundo Pancha Paula': 15083, 'Olfa': 15088, 'Rio Seco': 15123, 'Paraiso': 15004, 'El Rosario': 15011, 'Cerro Puquio': 15012, 'La Campana': 15019, 'Las Animas': 15022, 'Vetancio': 15023, 'Roma Alta': 15026, 'San Jose': 15476, 'San Pedro de Carabayllo': 15121, 'Huacoy': 15483, 'Fundo Pampa Libre': 15487, 'Ex Fundo Santa Ines': 15491, 'Reposo': 15494, 'Carmelito': 15498, 'Santa Elena': 15047, 'Don Luis': 15049, 'Santa Ines Parcela': 15063, 'Asociacion Santa Ines': 15082, 'Roma Baja': 15083, 'Residencial Santa Lucia': 15121, 'San Francisco': 15122, 'Santa Margarita - Molinos': 15313, 'Sipan Peru': 15316, 'Fundo Cuadros': 15318, 'Bello Horizonte': 15319, 'El Hueco': 15320, 'Ex Fundo Mariategui': 15321, 'Naranjito': 15324, 'Vista Hermosa': 15320, 'El Sabroso de Jose Carlos Mariategui': 15320, 'Granja Carabayllo': 15320, 'Agropecuario Valle el Chillon': 15320, 'Camino Real': 15320, 'Copacabana': 15320, 'El Trebol': 15121, 'Tablada la Virgen': 15320, 'San Fernando de Carabayllo': 15320, 'San Fernando de Copacabana': 15121, 'La Manzana': 15320, 'Chacra Grande': 15320, 'Torres de Copacabana': 15121, 'Chaclacayo': 15122, 'Chorrillos': 15121, 'Cieneguilla': 15121, 'Lindero': 15121, 'Pichicato': 15320, 'San Isidro': 15004, 'San Vicente': 15320, 'Piedra Liza': 15320, 'Santa Rosa de Chontay (Chontay)': 15320, 'La Libertad': 15320, 'El Agustino': 15121, 'Independencia': 15121, 'Jesus Maria': 15121, 'La Molina': 15320, 'La Victoria': 15121, 'Lince': 15319, 'Las Palmeras': 15121, 'Chosica': 15121, 'Lurin': 15121, 'Los Almacigos': 15320, 'Rinconada del Puruhuay': 15320, 'Fundo Santa Genoveva': 15121, 'Los Maderos': 15121, 'Casco Viejo': 15121, 'Vista Alegre': 15121, 'Buena Vista Alta': 15320, 'Lomas Pucara': 15320, 'Fundo la Querencia': 15320, 'Magdalena del Mar': 15122, 'Pueblo Libre': 15122, 'Miraflores': 15122, 'Pachacamac': 15122, 'Puente Manchay': 15122, 'Tambo Inga': 15122, 'Pampa Flores': 15122, 'Manchay Alto Lote B': 15122, 'Invasion Cementerio': 15121, 'Manchay Bajo': 15121, 'Santa Rosa de Mal Paso': 15122, 'Cardal': 15122, 'Jatosisa': 15121, 'Tomina': 15121, 'Pucusana': 15122, 'Honda': 15122, 'Quipa': 15121, 'Los Pelicanos': 15122, 'Playa Puerto Bello': 15122, 'Ñaves': 15122, 'Granja Santa Elena': 15472, 'Alvatroz II': 15476, 'Poseidon - Lobo Varado': 15054, 'Playa Minka Mar': 15056, 'Playa Acantilado': 15057, 'Puente Piedra': 15058, 'Punta Hermosa': 15063, 'Capilla Lucumo': 15064, 'Cucuya': 15066, 'Pampapacta': 15067, 'Avicola San Cirilo de Loma Negra - 03': 15593, 'Avicola San Cirilo de Loma Negra - 02': 15594, 'Avicola San Cirilo de Loma Negra - 01': 15593, 'Pampa Mamay': 15593, 'Cerro Botija': 15593, 'Agricultores y Ganaderos': 15593, 'Pampa Malanche Avicola Puma': 15593, 'Punta Negra': 15593, 'Chancheria': 15593, 'Rimac': 15311, 'San Bartolo': 15312, 'Plantel 41': 15313, 'Granja 4': 15314, 'Granja 5': 15316, 'Granja 07': 15324, 'Granja 44': 15326, 'Granja 47': 15327, 'Santa Maria I': 15328, 'Las Torres Santa Fe': 15332, 'San Francisco de Borja': 15003, 'San Juan de Lurigancho': 15006, 'Ciudad de Dios': 15007, 'San Luis': 15008, 'Barrio Obrero Industrial': 15009, 'San Miguel': 15011, 'Santa Anita - los Ficus': 15018, 'Santa Maria del Mar': 15022, 'Don Bruno': 15311, 'Santa Rosa': 15328, 'Santiago de Surco': 15331, 'Surquillo': 15332, 'Villa el Salvador': 15333, 'Villa Maria del Triunfo': 15046, 'Pueblo libre': 15001}
import numpy as np np.array( [1, 2, 3, 4, 5] ) # A library is a collection of modules or a single module. Libraries are the tools we will use to make our program.
array([1, 2, 3, 4, 5])
# 1D array (vector) a = np.array( [1, 2, 3, 4, 5] ) print(a)
[1 2 3 4 5]
type(a)
numpy.ndarray
np.mean(a) np.sum(a)
15
np.std(a)
1.4142135623730951

Standar deviation in Python by default

sd(x)=(xixˉ)2N1\begin{equation} sd(x) = \sqrt{\frac{\sum(x_i-\bar{x})^2}{N-1}} \end{equation}
np.std(a,ddof=1)
1.5811388300841898

Standar deviation in Python by default

sd(x)=(xixˉ)2N\begin{equation} sd(x) = \sqrt{\frac{\sum(x_i-\bar{x})^2}{N}} \end{equation}
# 2D array M = np.array( [ [1, 2, 3], [4, 5, 6] ] ) print(M)
[[1 2 3] [4 5 6]]
# dimensiones M.shape # numero de filas
(2, 3)
print("Rows:",M.shape[0],"\n", "Columns: ", M.shape[1])
Rows: 2 Columns: 3
# Create a 1D NumPy array with values from 0 to 20 (exclusively) incremented by 2: y = np.arange( 0, 20, 2 ) print(y)
[ 0 2 4 6 8 10 12 14 16 18]
# deafult one by one y = np.arange( 1, 11) print(y) list(range(11))
[ 1 2 3 4 5 6 7 8 9 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# rep() equivalent in python print( np.repeat(2, 4) ) print( np.repeat(range(11), 4) )
[2 2 2 2] [ 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 10 10 10 10]
print( np.tile(np.array([0,1]), 4) ) # split array np.array_split(np.arange( 0, 10), 4)
[0 1 0 1 0 1 0 1]
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7]), array([8, 9])]

Matrix

A = np.array([ np.arange(0,10), np.arange(10,20), np.arange(30,40), np.arange(-20,-10), np.arange(2,21,2)])
A
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [-20, -19, -18, -17, -16, -15, -14, -13, -12, -11], [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]])
A[2:5,:] # rows selecrtion
array([[ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [-20, -19, -18, -17, -16, -15, -14, -13, -12, -11], [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]])
A[:,0:6] # columns selecrtion
array([[ 0, 1, 2, 3, 4, 5], [ 10, 11, 12, 13, 14, 15], [ 30, 31, 32, 33, 34, 35], [-20, -19, -18, -17, -16, -15], [ 2, 4, 6, 8, 10, 12]])
M1 = np.zeros( (8, 2) ) print(M1)
[[0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.]]
M2 = np.ones( (8, 4) ) print(M2)
[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]

Join matrix

M3 = np.hstack((M1,M2)) # stack horizontal M3
array([[0., 0., 1., 1., 1., 1.], [0., 0., 1., 1., 1., 1.], [0., 0., 1., 1., 1., 1.], [0., 0., 1., 1., 1., 1.], [0., 0., 1., 1., 1., 1.], [0., 0., 1., 1., 1., 1.], [0., 0., 1., 1., 1., 1.], [0., 0., 1., 1., 1., 1.]])
M4 = np.array([[2,2,3,4,5,1],[1,5,5,9,8,2]]) print(M4)
[[2 2 3 4 5 1] [1 5 5 9 8 2]]
M5 = np.vstack((M3,M4)) # stack vertical print(M5) M5.T
[[0. 0. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1.] [0. 0. 1. 1. 1. 1.] [2. 2. 3. 4. 5. 1.] [1. 5. 5. 9. 8. 2.]]
array([[0., 0., 0., 0., 0., 0., 0., 0., 2., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 2., 5.], [1., 1., 1., 1., 1., 1., 1., 1., 3., 5.], [1., 1., 1., 1., 1., 1., 1., 1., 4., 9.], [1., 1., 1., 1., 1., 1., 1., 1., 5., 8.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 2.]])
# Create a 1D NumPy array of ones of length 10: w = np.ones(10) print(w)
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
# Create the identity matrix of size 8: I = np.eye(8) print(I)
[[1. 0. 0. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0.] [0. 0. 1. 0. 0. 0. 0. 0.] [0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0.] [0. 0. 0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 0. 0. 1. 0.] [0. 0. 0. 0. 0. 0. 0. 1.]]
I3 = I.reshape(32, 2) print(I3)
[[1. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 1.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [1. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 1.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [1. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 1.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [1. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 1.]]
np.random.seed(175) # semilla aleatoria para producir numeros aleatorios # permite que los numeros aleatorios no cambien al correr los códigos # numpy random permite generar números aleatorios unicos x1 = np.random.rand(500) x2 = np.random.rand(500) # uniform distribution [0,1] x3 = np.random.rand(500) # uniform distribution [0,1] x4 = np.random.rand(500) # uniform distribution [0,1] e = np.random.normal(0,1,500) # normal distribution mean = 0 and sd = 1 # Poblacional regression (Data Generating Process GDP) Y = 1 + 0.8*x1 + 1.2*x2 + 0.5*x3 + 1.5*x4 + e
X = np.column_stack((np.ones(500),x1,x2,x3,x4)) X
array([[1. , 0.04475417, 0.40772643, 0.34264416, 0.02414698], [1. , 0.28733056, 0.37711362, 0.50872145, 0.44327971], [1. , 0.07313766, 0.12851589, 0.82887389, 0.42140717], ..., [1. , 0.45844518, 0.72689186, 0.10918985, 0.68319966], [1. , 0.03768319, 0.24451085, 0.94042077, 0.94862136], [1. , 0.35377639, 0.60304925, 0.82421856, 0.49296456]])
beta = np.linalg.inv(X.T @ X) @ ((X.T) @ Y ) print(beta)
[0.96104291 0.91288635 1.08981519 0.47300876 1.53537517]