Kernel: Python 3 (ipykernel)
Geopandas y operaciones ARCGIS
@author: Roberto mendoza
In [4]:
no module name, solo instalelo usando !pip install
1.0 Polygonos
In [5]:
Out[5]:
In [6]:
Out[6]:
<Derived Projected CRS: EPSG:32718>
Name: WGS 84 / UTM zone 18S
Axis Info [cartesian]:
- E[east]: Easting (metre)
- N[north]: Northing (metre)
Area of Use:
- name: Between 78°W and 72°W, southern hemisphere between 80°S and equator, onshore and offshore. Argentina. Brazil. Chile. Colombia. Ecuador. Peru.
- bounds: (-78.0, -80.0, -72.0, 0.0)
Coordinate Operation:
- name: UTM zone 18S
- method: Transverse Mercator
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
Sistema de coordendas proyectada usada en la Mita
In [7]:
Out[7]:
In [8]:
Out[8]:
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [9]:
Out[9]:
In [10]:
Out[10]:
<Derived Projected CRS: EPSG:4087>
Name: WGS 84 / World Equidistant Cylindrical
Axis Info [cartesian]:
- X[east]: Easting (metre)
- Y[north]: Northing (metre)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Coordinate Operation:
- name: World Equidistant Cylindrical
- method: Equidistant Cylindrical
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [11]:
Out[11]:
In [12]:
Out[12]:
<AxesSubplot:>
2.0 Point
In [13]:
Out[13]:
In [14]:
Out[14]:
<Derived Projected CRS: PROJCS["mita_equi",GEOGCS["WGS 84",DATUM["WGS_1984 ...>
Name: mita_equi
Axis Info [cartesian]:
- [east]: Easting (metre)
- [north]: Northing (metre)
Area of Use:
- undefined
Coordinate Operation:
- name: unnamed
- method: Equidistant Cylindrical
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [15]:
Out[15]:
In [16]:
Out[16]:
<AxesSubplot:>
In [17]:
In [18]:
Out[18]:
3.0 Linestring
In [19]:
In [20]:
Out[20]:
In [21]:
Out[21]:
<AxesSubplot:>
In [22]:
Out[22]:
<Derived Projected CRS: EPSG:32718>
Name: WGS 84 / UTM zone 18S
Axis Info [cartesian]:
- E[east]: Easting (metre)
- N[north]: Northing (metre)
Area of Use:
- name: Between 78°W and 72°W, southern hemisphere between 80°S and equator, onshore and offshore. Argentina. Brazil. Chile. Colombia. Ecuador. Peru.
- bounds: (-78.0, -80.0, -72.0, 0.0)
Coordinate Operation:
- name: UTM zone 18S
- method: Transverse Mercator
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [23]:
Out[23]:
In [24]:
Out[24]:
3.0 Merge Geospatial information
In [25]:
In [26]:
Out[26]:
In [27]:
Out[27]:
In [28]:
Out[28]:
<class 'geopandas.geodataframe.GeoDataFrame'>
RangeIndex: 305 entries, 0 to 304
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Point 305 non-null geometry
1 UBIGEO 305 non-null float64
2 geometry 305 non-null geometry
dtypes: float64(1), geometry(2)
memory usage: 7.3 KB
3.1 Join - Contains
In [29]:
Out[29]:
3.2 Join - whitin
In [30]:
Out[30]:
3.3 Join - Intersects
In [31]:
Out[31]:
In [32]:
Out[32]:
<AxesSubplot:>
In [33]:
Out[33]:
<AxesSubplot:>
In [34]:
Out[34]:
<Derived Projected CRS: EPSG:32718>
Name: WGS 84 / UTM zone 18S
Axis Info [cartesian]:
- E[east]: Easting (metre)
- N[north]: Northing (metre)
Area of Use:
- name: Between 78°W and 72°W, southern hemisphere between 80°S and equator, onshore and offshore. Argentina. Brazil. Chile. Colombia. Ecuador. Peru.
- bounds: (-78.0, -80.0, -72.0, 0.0)
Coordinate Operation:
- name: UTM zone 18S
- method: Transverse Mercator
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
In [35]:
In [33]:
Out[33]:
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Input In [33], in <cell line: 16>()
11 mita_boundary.plot(color = '#834333' ,linewidth=4, ax = ax, label='Mita Boundary target')
13 # añade un mapa de fondo
14
15 # contextuly
---> 16 cx.add_basemap(ax, crs="EPSG:4326", attribution = False, zoom = 11)
18 # sin valores en los ejes
20 plt.xticks([])
File ~\anaconda3\envs\env_geopandas\lib\site-packages\contextily\plotting.py:121
, in add_basemap(ax, zoom, source, interpolation, attribution, attribution_size, reset_extent, crs, resampling, **extra_imshow_args)
117 left, right, bottom, top = _reproj_bb(
118 left, right, bottom, top, crs, {"init": "epsg:3857"}
119 )
120 # Download image
--> 121 image, extent = bounds2img(
122 left, bottom, right, top, zoom=zoom, source=source, ll=False
123 )
124 # Warping
125 if crs is not None:
File ~\anaconda3\envs\env_geopandas\lib\site-packages\contextily\tile.py:222
, in bounds2img(w, s, e, n, zoom, source, ll, wait, max_retries)
220 x, y, z = t.x, t.y, t.z
221 tile_url = provider.build_url(x=x, y=y, z=z)
--> 222 image = _fetch_tile(tile_url, wait, max_retries)
223 tiles.append(t)
224 arrays.append(image)
File ~\anaconda3\envs\env_geopandas\lib\site-packages\joblib\memory.py:594
, in MemorizedFunc.__call__(self, *args, **kwargs)
593 def __call__(self, *args, **kwargs):
--> 594 return self._cached_call(args, kwargs)[0]
File ~\anaconda3\envs\env_geopandas\lib\site-packages\joblib\memory.py:537
, in MemorizedFunc._cached_call(self, args, kwargs, shelving)
534 must_call = True
536 if must_call:
--> 537 out, metadata = self.call(*args, **kwargs)
538 if self.mmap_mode is not None:
539 # Memmap the output at the first call to be consistent with
540 # later calls
541 if self._verbose:
File ~\anaconda3\envs\env_geopandas\lib\site-packages\joblib\memory.py:779
, in MemorizedFunc.call(self, *args, **kwargs)
777 if self._verbose > 0:
778 print(format_call(self.func, args, kwargs))
--> 779 output = self.func(*args, **kwargs)
780 self.store_backend.dump_item(
781 [func_id, args_id], output, verbose=self._verbose)
783 duration = time.time() - start_time
File ~\anaconda3\envs\env_geopandas\lib\site-packages\contextily\tile.py:252
, in _fetch_tile(tile_url, wait, max_retries)
250 @memory.cache
251 def _fetch_tile(tile_url, wait, max_retries):
--> 252 request = _retryer(tile_url, wait, max_retries)
253 with io.BytesIO(request.content) as image_stream:
254 image = Image.open(image_stream).convert("RGBA")
File ~\anaconda3\envs\env_geopandas\lib\site-packages\contextily\tile.py:395
, in _retryer(tile_url, wait, max_retries)
375 """
376 Retry a url many times in attempt to get a tile
377
(...)
392 request object containing the web response.
393 """
394 try:
--> 395 request = requests.get(tile_url, headers={"user-agent": USER_AGENT})
396 request.raise_for_status()
397 except requests.HTTPError:
File ~\anaconda3\envs\env_geopandas\lib\site-packages\requests\api.py:75
, in get(url, params, **kwargs)
64 def get(url, params=None, **kwargs):
65 r"""Sends a GET request.
66
67 :param url: URL for the new :class:`Request` object.
(...)
72 :rtype: requests.Response
73 """
---> 75 return request('get', url, params=params, **kwargs)
File ~\anaconda3\envs\env_geopandas\lib\site-packages\requests\api.py:61
, in request(method, url, **kwargs)
57 # By using the 'with' statement we are sure the session is closed, thus we
58 # avoid leaving sockets open which can trigger a ResourceWarning in some
59 # cases, and look like a memory leak in others.
60 with sessions.Session() as session:
---> 61 return session.request(method=method, url=url, **kwargs)
File ~\anaconda3\envs\env_geopandas\lib\site-packages\requests\sessions.py:529
, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
524 send_kwargs = {
525 'timeout': timeout,
526 'allow_redirects': allow_redirects,
527 }
528 send_kwargs.update(settings)
--> 529 resp = self.send(prep, **send_kwargs)
531 return resp
File ~\anaconda3\envs\env_geopandas\lib\site-packages\requests\sessions.py:645
, in Session.send(self, request, **kwargs)
642 start = preferred_clock()
644 # Send the request
--> 645 r = adapter.send(request, **kwargs)
647 # Total elapsed time of the request (approximately)
648 elapsed = preferred_clock() - start
File ~\anaconda3\envs\env_geopandas\lib\site-packages\requests\adapters.py:440
, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
438 try:
439 if not chunked:
--> 440 resp = conn.urlopen(
441 method=request.method,
442 url=url,
443 body=request.body,
444 headers=request.headers,
445 redirect=False,
446 assert_same_host=False,
447 preload_content=False,
448 decode_content=False,
449 retries=self.max_retries,
450 timeout=timeout
451 )
453 # Send the request.
454 else:
455 if hasattr(conn, 'proxy_pool'):
File ~\anaconda3\envs\env_geopandas\lib\site-packages\urllib3\connectionpool.py:703
, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
700 self._prepare_proxy(conn)
702 # Make the request on the httplib connection object.
--> 703 httplib_response = self._make_request(
704 conn,
705 method,
706 url,
707 timeout=timeout_obj,
708 body=body,
709 headers=headers,
710 chunked=chunked,
711 )
713 # If we're going to release the connection in ``finally:``, then
714 # the response doesn't need to know about the connection. Otherwise
715 # it will also try to release it and we'll have a double-release
716 # mess.
717 response_conn = conn if not release_conn else None
File ~\anaconda3\envs\env_geopandas\lib\site-packages\urllib3\connectionpool.py:386
, in HTTPConnectionPool._make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
384 # Trigger any extra validation we need to do.
385 try:
--> 386 self._validate_conn(conn)
387 except (SocketTimeout, BaseSSLError) as e:
388 # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
389 self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
File ~\anaconda3\envs\env_geopandas\lib\site-packages\urllib3\connectionpool.py:1040
, in HTTPSConnectionPool._validate_conn(self, conn)
1038 # Force connect early to allow us to validate the connection.
1039 if not getattr(conn, "sock", None): # AppEngine might not have `.sock`
-> 1040 conn.connect()
1042 if not conn.is_verified:
1043 warnings.warn(
1044 (
1045 "Unverified HTTPS request is being made to host '%s'. "
(...)
1050 InsecureRequestWarning,
1051 )
File ~\anaconda3\envs\env_geopandas\lib\site-packages\urllib3\connection.py:358
, in HTTPSConnection.connect(self)
356 def connect(self):
357 # Add certificate verification
--> 358 self.sock = conn = self._new_conn()
359 hostname = self.host
360 tls_in_tls = False
File ~\anaconda3\envs\env_geopandas\lib\site-packages\urllib3\connection.py:174
, in HTTPConnection._new_conn(self)
171 extra_kw["socket_options"] = self.socket_options
173 try:
--> 174 conn = connection.create_connection(
175 (self._dns_host, self.port), self.timeout, **extra_kw
176 )
178 except SocketTimeout:
179 raise ConnectTimeoutError(
180 self,
181 "Connection to %s timed out. (connect timeout=%s)"
182 % (self.host, self.timeout),
183 )
File ~\anaconda3\envs\env_geopandas\lib\site-packages\urllib3\util\connection.py:85
, in create_connection(address, timeout, source_address, socket_options)
83 if source_address:
84 sock.bind(source_address)
---> 85 sock.connect(sa)
86 return sock
88 except socket.error as e:
KeyboardInterrupt:
In [ ]:
4.0 Distances
In [36]:
Out[36]:
In [37]:
Out[37]:
In [38]:
Out[38]:
In [39]:
Out[39]:
In [40]:
Out[40]:
0.3780424516996454
0.7991220422560418
In [41]:
In [42]:
Out[42]:
(-73.185, -13.95583333)
Referencia
In [43]:
Out[43]:
Distancia en kilometros: 202.10753203071803
Distancia en metros: 202107.53203071802
Distancia en millas: 125.58379809010545
In [44]:
Out[44]:
Distancia geodésica en kilometros : 202.86294742689847
Distancia great-circle en kilometros : 202.1075383753187
Referencia de Geopy
In [45]:
Out[45]:
6.399277433462688
0.011908123743330926
In [46]:
In [47]:
Out[47]:
87884.59488352262
5.0 Proyecciones a un plano cartesiano (Distancias Euclideanas)
In [48]:
In [49]:
Out[49]:
In [50]:
Out[50]:
In [51]:
Out[51]:
In [52]:
Out[52]:
Distancia minima euclideana en metros al Boundary : 87900.81102564473
In [53]:
Out[53]:
698.6938671485821
142.42277155133257
In [54]:
Out[54]:
87900.81102564473
7.0 Buffers
In [55]:
Out[55]:
([], [])
In [79]:
Out[79]:
([], [])
8.0 Geocoding
1.0 Free geocoding and Google API
In [57]:
Out[57]:
In [58]:
Out[58]:
In [59]:
Out[59]:
array(['SN', '1', '2', '6', 'NULL', '7', '8', '4', '13', '3', '21', '5',
'11', '20', '10', '55', '9', '33', '14', '28', '49', '41', '38',
'40', '31', '16', '15', '39', '3,', '2,', '5,', '1,', '33,', '6,',
'31,', '4,', '20,', '8,', '18,', '16,', '40,', '7,', '9,', '19,',
'30,'], dtype=object)
In [60]:
Out[60]:
In [61]:
Out[61]:
In [63]:
Out[63]:
In [64]:
Out[64]:
'PUCP Peru, Avenida Universitaria, 15032, Avenida Universitaria, San Miguel, Lima, Perú'
In [65]:
Out[65]:
[{'address_components': [{'long_name': '1801',
'short_name': '1801',
'types': ['street_number']},
{'long_name': 'Avenida Universitaria',
'short_name': 'Av. Universitaria',
'types': ['route']},
{'long_name': 'Fund Pando',
'short_name': 'Fund Pando',
'types': ['political', 'sublocality', 'sublocality_level_1']},
{'long_name': 'San Miguel',
'short_name': 'San Miguel',
'types': ['locality', 'political']},
{'long_name': 'Provincia de Lima',
'short_name': 'Provincia de Lima',
'types': ['administrative_area_level_2', 'political']},
{'long_name': 'Provincia de Lima',
'short_name': 'Provincia de Lima',
'types': ['administrative_area_level_1', 'political']},
{'long_name': 'Peru',
'short_name': 'PE',
'types': ['country', 'political']},
{'long_name': '15088', 'short_name': '15088', 'types': ['postal_code']}],
'formatted_address': 'Av. Universitaria 1801, San Miguel 15088, Peru',
'geometry': {'location': {'lat': -12.0689502, 'lng': -77.0780608},
'location_type': 'ROOFTOP',
'viewport': {'northeast': {'lat': -12.0676218697085,
'lng': -77.07669776970849},
'southwest': {'lat': -12.0703198302915, 'lng': -77.0793957302915}}},
'partial_match': True,
'place_id': 'ChIJpUAI1BLJBZERLobll7e_oNc',
'plus_code': {'compound_code': 'WWJC+CQ San Miguel',
'global_code': '57V4WWJC+CQ'},
'types': ['establishment', 'point_of_interest', 'university']}]
In [66]:
Out[66]:
{'address_components': [{'long_name': '1801',
'short_name': '1801',
'types': ['street_number']},
{'long_name': 'Avenida Universitaria',
'short_name': 'Av. Universitaria',
'types': ['route']},
{'long_name': 'Fund Pando',
'short_name': 'Fund Pando',
'types': ['political', 'sublocality', 'sublocality_level_1']},
{'long_name': 'San Miguel',
'short_name': 'San Miguel',
'types': ['locality', 'political']},
{'long_name': 'Provincia de Lima',
'short_name': 'Provincia de Lima',
'types': ['administrative_area_level_2', 'political']},
{'long_name': 'Provincia de Lima',
'short_name': 'Provincia de Lima',
'types': ['administrative_area_level_1', 'political']},
{'long_name': 'Peru', 'short_name': 'PE', 'types': ['country', 'political']},
{'long_name': '15088', 'short_name': '15088', 'types': ['postal_code']}],
'formatted_address': 'Av. Universitaria 1801, San Miguel 15088, Peru',
'geometry': {'location': {'lat': -12.0689502, 'lng': -77.0780608},
'location_type': 'ROOFTOP',
'viewport': {'northeast': {'lat': -12.0676218697085,
'lng': -77.07669776970849},
'southwest': {'lat': -12.0703198302915, 'lng': -77.0793957302915}}},
'partial_match': True,
'place_id': 'ChIJpUAI1BLJBZERLobll7e_oNc',
'plus_code': {'compound_code': 'WWJC+CQ San Miguel',
'global_code': '57V4WWJC+CQ'},
'types': ['establishment', 'point_of_interest', 'university']}
In [67]:
Out[67]:
dict_keys(['address_components', 'formatted_address', 'geometry', 'partial_match', 'place_id', 'plus_code', 'types'])
In [68]:
Out[68]:
{'lat': -12.0689502, 'lng': -77.0780608}
In [69]:
Out[69]:
(-77.0780608, -12.0689502)
In [70]:
Out[70]:
['establishment', 'point_of_interest', 'university']
In [71]:
Out[71]:
{'long_name': 'Provincia de Lima',
'short_name': 'Provincia de Lima',
'types': ['administrative_area_level_2', 'political']}
In [72]:
Out[72]:
In [73]:
In [74]:
Out[74]:
In [75]:
In [76]:
Out[76]:
Pandas Apply: 0%| | 0/20 [00:00<?, ?it/s]
Pandas Apply: 0%| | 0/20 [00:00<?, ?it/s]
In [77]:
In [78]:
Out[78]: