Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
robertopucp
GitHub Repository: robertopucp/1eco35_2022_2
Path: blob/main/Lab1/spyder_lab1.py
2714 views
1
# -*- coding: utf-8 -*-
2
"""
3
# Laboratorio 1 Python
4
5
## Types of variables
6
7
@author: Roberto Mendoza
8
"""
9
#%% Types of variables
10
11
########################################################
12
"""
13
1.0 Types of variables
14
"""
15
16
a1 = 3.141
17
type(a1)
18
19
20
a2 = 3.1416165516
21
type(a2)
22
23
# from float to int
24
25
c = int(a2)
26
type(c)
27
28
b1 = 10000
29
type(b1)
30
31
# from int to float
32
33
float(b1)
34
35
b2 = 8
36
type(b2)
37
38
c1 = "My first python code"
39
print(c1) # show that varaible's content
40
type(c1) # providing varaibles's type
41
42
# including a space using \n
43
44
c1 = "First python code"
45
c2 = "at R y python Class"
46
print(c1,'\n',c2)
47
48
# join string
49
50
print(c1 + " : " + c2)
51
52
53
# f-using
54
55
56
print(f'{c1} : semester 2022-1')
57
58
d = 2022
59
60
print(f'{c1} : semester {d}-1')
61
62
print('{} : semester {}-1'.format(c1,d))
63
64
c1[0:5]
65
66
#first character
67
print('Fisrt letter is :',c1[0])
68
69
#first word
70
print('Fisrt word is :',c1[0:5])
71
72
73
#%% Bool variables
74
75
########################################################
76
"""
77
2. 0 Bool variables
78
"""
79
80
"a" == "a"
81
82
1 > 1
83
84
z1 = (1==1)
85
int(z1)
86
87
z2 = (10 > 20)
88
int(z2)
89
90
z3 = (100 != 100)
91
int(z3)
92
93
94
#%% Tuple
95
96
########################################################
97
"""
98
3.0 Tuple
99
"""
100
101
#### It is an ordered and immutable Python object
102
103
T1 = (1,4,8,10,20,15,4,5,3,8)
104
print(T1)
105
type(T1)
106
107
# aritmethic operations
108
109
print('Suma:', sum(T1),"\n", "Minimo:", min(T1), '\n', "Maximo:", max(T1))
110
111
len(T1) # lenght of tuple
112
113
"""
114
Indexing tuple
115
"""
116
117
T1[0:5] # give us elements from 0 position until 4 position
118
119
T1[1] # get tuple's element
120
121
T1[0:3]
122
123
# It is not possible to change
124
T1[0] = 4
125
126
T1[-1] # last element
127
128
#position
129
T1.index(8)
130
131
132
#%% List
133
"""
134
4.0 List
135
"""
136
137
#### It is an ordered and mutable Python container.
138
139
L1 = []
140
print(L1)
141
type(L1)
142
143
dis1 = ["ATE", 'BARRANCO','BREÑA', 'CALLAO', 'CARABAYLLO']
144
dis1
145
146
dis2 = ['ATE', 'BARRANCO','BREÑA', 'CALLAO', 'CARABAYLLO','CHACLACAYO','CHORRILLOS','CIENEGUILLA'
147
,'COMAS','EL_AGUSTINO','INDEPENDENCIA']
148
print(dis2)
149
len(dis2)
150
151
dis2[1]
152
153
# Change elements
154
dis2[0] = "CALLAO"
155
print(dis2)
156
157
# Indexing
158
159
dis2[1]
160
161
dis2[2:5] #(5-1=4)
162
163
dis2[-1]
164
165
dis2[-5:-1]
166
167
## sorting
168
169
num = [13,5,5,8,9,10,5,8,13,1,20]
170
num.sort()
171
print(num)
172
173
## append new elements
174
175
num.append(102)
176
print(num)
177
178
## append new lists
179
180
num2 = [10,20,30]
181
num.extend(num2)
182
print(num)
183
184
print(num.index(102))
185
186
print("Suma:", sum(num),'\n', "Minimo:", min(num), '\n', "Maximo:", max(num))
187
188
#%% Diccionario
189
########################################################
190
## 5.0 Dictionarities
191
192
Postal_code = {'Majes': 40520, 'Mollendo': 40701, 'Islay': 40704, 'Cotahuasi': 40801, 'Alca': 40802 }
193
type(Postal_code)
194
195
Postal_code
196
Postal_code.keys()
197
198
# Get information from key
199
Postal_code['Alca']
200
Postal_code.get('Alca')
201
202
# Drop key
203
Postal_code.pop('Islay')
204
Postal_code
205
206
# add new elements
207
Postal_code.update( { "CHARCANA" : 40803 } )
208
209
#diccioanrio dentro de otro diccionario
210
211
Postal_code.update( {"LOMAS": {"UBIGEO": 40311, "Poverty Rate" : "18.2%", "Population" : "20 mil"}})
212
213
Postal_code.get('LOMAS').get('Poverty Rate')
214
215
Postal_code['LOMAS']['Poverty Rate']
216
217
# keys
218
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']
219
# values
220
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]
221
222
# Return a dictionarie
223
ct_pc = dict( zip( cities , postal_code1) )
224
225
ct_pc
226
227
#%% Numpy
228
########################################################
229
## 6.0 Numpy (array, matrices)
230
231
import numpy as np
232
233
# 1D array
234
a = np.array( [1, 2, 3, 4, 5] )
235
print(a)
236
237
238
np.mean(a)
239
np.std(a)
240
np.std(a,ddof=1)
241
242
# 2D array
243
M = np.array( [ [1, 2, 3], [4, 5, 6] ] )
244
245
print(M)
246
type(M)
247
# dimensiones
248
M.shape
249
250
# Create a 1D NumPy array with values from 0 to 20 (exclusively) incremented by 2:
251
y = np.arange( 0, 20, 2 )
252
print(y.shape)
253
print(y)
254
255
y[0]
256
257
np.array_split
258
259
# deafult one by one
260
261
y = np.arange( 1, 11)
262
print(y)
263
264
np.arange(11)
265
range(11)
266
267
"""
268
Repeat elements np.repeat(number, times) , np.tile(number : vector , times)
269
"""
270
271
np.repeat(2, 4)
272
np.repeat(range(11), 4)
273
274
np.tile(np.array([1,2]), 4)
275
np.tile(range(11),5)
276
277
"""
278
Split array
279
"""
280
281
np.array_split(np.arange( 100, 1000),50)
282
283
"""
284
# Mattrix
285
"""
286
287
A = np.array([np.arange(0,10), np.arange(10,20), np.arange(30,40), np.arange(-20,-10), np.arange(2,21,2)])
288
A
289
290
A[2:5,:] # rows selecrtion
291
292
293
A[:,0:6] # columns selecrtion
294
295
M1 = np.zeros( (8, 2) )
296
print(M1)
297
298
M2 = np.ones( (8, 4) )
299
print(M2)
300
301
## Join matrix
302
303
M3 = np.hstack((M1,M2))
304
M3
305
306
307
# vstack
308
309
M4 = np.array([[2,2,3,4,5,1],[1,5,5,9,8,2]])
310
print(M4)
311
312
M5 = np.vstack((M3,M4))
313
print(M5)
314
M5.T
315
316
# Create a 1D NumPy array of ones of length 10:
317
w = np.ones(10)
318
print(w)
319
type(w)
320
321
# Create the identity matrix of size 8:
322
I = np.eye(8)
323
print(I)
324
325
# Reshape
326
327
I3 = I.reshape(32, 2)
328
print(I3)
329
330
#Transpose
331
print(I3.T)
332
(I3.T).shape
333
334
#%% OlS
335
336
import random
337
338
np.random.seed(175)
339
340
x1 = np.random.rand(500) # uniform distribution [0,1]
341
x2 = np.random.rand(500) # uniform distribution [0,1]
342
x3 = np.random.rand(500) # uniform distribution [0,1]
343
x4 = np.random.rand(500) # uniform distribution [0,1]
344
e = np.random.normal(0,1,500) # normal distribution mean = 0 and sd = 1
345
346
# Poblacional regression (Data Generating Process GDP)
347
348
349
Y = 1 + 0.8*x1 + 1.2*x2 + 0.5*x3 + 1.5*x4 + e
350
351
X = np.column_stack((np.ones(500),x1,x2,x3,x4))
352
X
353
354
beta = np.linalg.inv(X.T @ X) @ ((X.T) @ Y )
355
print(beta)
356
357