Python geopandas.GeoSeries() Examples
The following are 30
code examples of geopandas.GeoSeries().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
geopandas
, or try the search function
.
Example #1
Source File: test_utils.py From momepy with MIT License | 7 votes |
def test_network_false_nodes(self): test_file_path2 = mm.datasets.get_path("tests") self.false_network = gpd.read_file(test_file_path2, layer="network") fixed = mm.network_false_nodes(self.false_network) assert len(fixed) == 55 assert isinstance(fixed, gpd.GeoDataFrame) assert self.false_network.crs.equals(fixed.crs) fixed_series = mm.network_false_nodes(self.false_network.geometry) assert len(fixed_series) == 55 assert isinstance(fixed_series, gpd.GeoSeries) assert self.false_network.crs.equals(fixed_series.crs) with pytest.raises(TypeError): mm.network_false_nodes(list()) multiindex = self.false_network.explode() fixed_multiindex = mm.network_false_nodes(multiindex) assert len(fixed_multiindex) == 55 assert isinstance(fixed, gpd.GeoDataFrame)
Example #2
Source File: _geopandas.py From regionmask with MIT License | 6 votes |
def _prepare_gdf_for_mask(geodataframe, method, numbers): from geopandas import GeoDataFrame, GeoSeries if not isinstance(geodataframe, (GeoDataFrame, GeoSeries)): raise TypeError("input must be a geopandas 'GeoDataFrame' or 'GeoSeries'") if method == "legacy": raise ValueError("method 'legacy' not supported in 'mask_geopandas'") lon_min = geodataframe.bounds["minx"].min() lon_max = geodataframe.bounds["maxx"].max() is_180 = _is_180(lon_min, lon_max) polygons = geodataframe.geometry.tolist() if numbers is not None: numbers = geodataframe[numbers] _check_missing(numbers, "numbers") _check_duplicates(numbers, "numbers") else: numbers = geodataframe.index.values return polygons, is_180, numbers
Example #3
Source File: test_holes.py From maup with MIT License | 6 votes |
def test_threshold(self): # 000 # 00x1 # 00x1 square1 = square_at((0, 0), side_length=3) square2 = square_at((2, 0), side_length=2) geometries = geopandas.GeoSeries([square1, square2]) # This threshold is low enough that nothing should happen: result = resolve_overlaps(geometries, relative_threshold=0.0001) # Expected: # 000 # 00x1 # 00x1 print(result) assert result[0].equals(square1) assert result[1].equals(square2)
Example #4
Source File: test_holes.py From maup with MIT License | 6 votes |
def test_threshold_rules_out_one_but_not_both(self): # 000 # 00x1 # 00x1 square1 = square_at((0, 0), side_length=3) square2 = square_at((2, 0), side_length=2) geometries = geopandas.GeoSeries([square1, square2]) # It's under threshold w.r.t square1 but not square 2 result = resolve_overlaps(geometries, relative_threshold=0.4) # Expected: # 000 # 00x1 # 00x1 assert result[0].equals(square1) assert result[1].equals(square2)
Example #5
Source File: test_holes.py From maup with MIT License | 6 votes |
def test_assigns_overlap_by_max_shared_perimeter(self): """The overlapping area should be assigned to the polygon that shares the most perimeter with the overlap. """ # 000 # 00x1 # 00x1 square1 = square_at((0, 0), side_length=3) square2 = square_at((2, 0), side_length=2) geometries = geopandas.GeoSeries([square1, square2]) result = resolve_overlaps(geometries, relative_threshold=None) # Expected: # 000 # 0001 # 0001 assert result[0].equals(square1) assert result[1].equals(Polygon([(3, 0), (3, 2), (4, 2), (4, 0)]))
Example #6
Source File: geoplot.py From geoplot with MIT License | 6 votes |
def paint_clip(self): clip = self.kwargs.pop('clip') clip = _to_geom_geoseries(self.df, clip, "clip") if clip is not None: if self.projection is not None: xmin, xmax, ymin, ymax = self.ax.get_extent(crs=ccrs.PlateCarree()) extent = (xmin, ymin, xmax, ymax) clip_geom = self._get_clip(extent, clip) feature = ShapelyFeature([clip_geom], ccrs.PlateCarree()) self.ax.add_feature(feature, facecolor=(1,1,1), linewidth=0, zorder=2) else: xmin, xmax = self.ax.get_xlim() ymin, ymax = self.ax.get_ylim() extent = (xmin, ymin, xmax, ymax) clip_geom = self._get_clip(extent, clip) xmin, xmax = self.ax.get_xlim() ymin, ymax = self.ax.get_ylim() polyplot( gpd.GeoSeries(clip_geom), facecolor='white', linewidth=0, zorder=2, extent=extent, ax=self.ax )
Example #7
Source File: test_holes.py From maup with MIT License | 6 votes |
def test_can_impose_relative_area_threshold(self): # 001 # 0 1 # 001 pacman = Polygon( [(0, 0), (0, 3), (2, 3), (2, 2), (1, 2), (1, 1), (2, 1), (2, 0)] ) bar = Polygon([(2, 0), (2, 3), (3, 3), (3, 0)]) geometries = geopandas.GeoSeries([pacman, bar]) fixed = close_gaps(geometries, relative_threshold=0.01) # Since the gap is more than 1% of the area, the gap is not closed assert fixed[1].equals(bar) assert fixed[0].equals(pacman) geometries = geopandas.GeoSeries([pacman, bar]) fixed = close_gaps(geometries, relative_threshold=0.5) # Since the gap is less than 50% of the area, the gap is closed assert fixed[1].equals(bar) assert fixed[0].equals(Polygon([(0, 0), (0, 3), (2, 3), (2, 0)]))
Example #8
Source File: test_holes.py From maup with MIT License | 6 votes |
def test_multipolygon(self): # 000 000 # 0 0 0 0 # 000 000 geometries = geopandas.GeoSeries( [ square_at(point) for point in product([0, 1, 2], [0, 1, 2]) if point != (1, 1) ] + [ square_at(point) for point in product([4, 5, 6], [0, 1, 2]) if point != (5, 1) ] ) result = holes_of_union(geometries) assert len(result) == 2 squares = [square_at((1, 1)), square_at((5, 1))] assert (result[0].equals(squares[0]) and result[1].equals(squares[1])) or ( result[1].equals(squares[0]) and result[0].equals(squares[1]) )
Example #9
Source File: utils.py From geoplot with MIT License | 6 votes |
def gaussian_polygons(points, n=10): """ Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point` objects. """ gdf = gpd.GeoDataFrame( data={'cluster_number': classify_clusters(points, n=n)}, geometry=points ) polygons = [] for i in range(n): sel_points = gdf[gdf['cluster_number'] == i].dropna().geometry polygons.append(shapely.geometry.MultiPoint([(p.x, p.y) for p in sel_points]).convex_hull) polygons = [ p for p in polygons if ( (not isinstance(p, shapely.geometry.Point)) and (not isinstance(p, shapely.geometry.LineString))) ] return gpd.GeoSeries(polygons)
Example #10
Source File: test_holes.py From maup with MIT License | 6 votes |
def test_multiple_holes_of_union(self): # 00000 # 0 0 0 # 00000 geometries = geopandas.GeoSeries( [ square_at(point) for point in product([0, 1, 2, 3, 4], [0, 1, 2]) if point not in [(1, 1), (3, 1)] ] ) result = holes_of_union(geometries) assert len(result) == 2 squares = [square_at((1, 1)), square_at((3, 1))] assert (result[0].equals(squares[0]) and result[1].equals(squares[1])) or ( result[1].equals(squares[0]) and result[0].equals(squares[1]) )
Example #11
Source File: test_subscriber_location_cluster.py From FlowKit with Mozilla Public License 2.0 | 6 votes |
def test_cluster_is_within_envelope(get_dataframe): """ Test that all the clusters are within the enveloped formed by all the towers in the cluster. """ cd = CallDays( SubscriberLocations( "2016-01-01", "2016-01-04", spatial_unit=make_spatial_unit("versioned-site") ) ) hartigan = HartiganCluster(calldays=cd, radius=50) har_df = hartigan.to_geopandas() sites = Sites().to_geopandas().set_index(["site_id", "version"]) towers = GeoSeries(har_df.apply(lambda x: get_geom_point(x, sites), 1)) s = har_df.intersects(towers) assert all(s)
Example #12
Source File: test_types.py From cate with MIT License | 6 votes |
def test_fat_ops(self): features = read_test_features() gdf = GeoDataFrame.from_features(features) self.assertIsNotNone(gdf.crs) from cate.ops.data_frame import data_frame_min, data_frame_max df_min = data_frame_min(gdf, 'C') self.assertIsInstance(df_min, gpd.GeoDataFrame) self.assertEqual(len(df_min), 1) # assertCountEqual ignores the order of the list self.assertCountEqual(list(df_min.columns), ['A', 'B', 'C', 'geometry']) self.assertIsInstance(df_min.geometry, gpd.GeoSeries) self.assertIsNotNone(df_min.crs) df_max = data_frame_max(gdf, 'C') self.assertIsInstance(df_max, gpd.GeoDataFrame) self.assertEqual(len(df_max), 1) # assertCountEqual ignores the order of the list self.assertCountEqual(list(df_max.columns), ['A', 'B', 'C', 'geometry']) self.assertIsInstance(df_max.geometry, gpd.GeoSeries) self.assertIsNotNone(df_max.crs)
Example #13
Source File: test_eodata.py From eo-learn with MIT License | 6 votes |
def test_vector_feature_types(self): eop = EOPatch() invalid_entries = [ {}, [], 0, None ] for feature_type in FeatureTypeSet.VECTOR_TYPES: for entry in invalid_entries: with self.assertRaises(ValueError, msg='Invalid entry {} for {} should raise an error'.format(entry, feature_type)): eop[feature_type]['TEST'] = entry crs_test = CRS.WGS84.pyproj_crs() geo_test = GeoSeries([BBox((1, 2, 3, 4), crs=CRS.WGS84).geometry], crs=crs_test) eop.vector_timeless['TEST'] = geo_test self.assertTrue(isinstance(eop.vector_timeless['TEST'], GeoDataFrame), 'GeoSeries should be parsed into GeoDataFrame') self.assertTrue(hasattr(eop.vector_timeless['TEST'], 'geometry'), 'Feature should have geometry attribute') self.assertEqual(eop.vector_timeless['TEST'].crs, crs_test, 'GeoDataFrame should still contain the crs') with self.assertRaises(ValueError, msg='Should fail because there is no TIMESTAMP column'): eop.vector['TEST'] = geo_test
Example #14
Source File: geopandas.py From geoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def geo_column(cls, data): from geopandas import GeoSeries col = 'geometry' if col in data and isinstance(data[col], GeoSeries): return col cols = [c for c in data.columns if isinstance(data[c], GeoSeries)] if not cols and len(data): raise ValueError('No geometry column found in geopandas.DataFrame, ' 'use the PandasInterface instead.') return cols[0] if cols else None
Example #15
Source File: test_indexed_geometries.py From maup with MIT License | 5 votes |
def test_returns_empty_when_no_overlaps_but_bounds_overlap( diamond, polygon_inside_diamond_bounds ): indexed = IndexedGeometries(GeoSeries([diamond])) assert len(indexed.intersections(polygon_inside_diamond_bounds)) == 0
Example #16
Source File: geopandas.py From geoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def applies(cls, obj): if not cls.loaded(): return False from geopandas import GeoDataFrame, GeoSeries return isinstance(obj, (GeoDataFrame, GeoSeries))
Example #17
Source File: conftest.py From maup with MIT License | 5 votes |
def square_mostly_in_top_left(): return gp.GeoSeries([Polygon([(1.5, 0.5), (1.5, 2), (0, 2), (0, 0.5)])], crs=CRS)
Example #18
Source File: conftest.py From maup with MIT License | 5 votes |
def squares_within_four_square_grid(): return gp.GeoSeries( [ # both fit inside a: Polygon([(0, 0), (0, 0.5), (0.5, 0.5), (0.5, 0)]), Polygon([(0.5, 0.5), (1, 0.5), (1, 1), (0.5, 1)]), # is exactly b: Polygon([(0, 1), (0, 2), (1, 2), (1, 1)]), # fits neatly inside d: Polygon([(1.25, 1.25), (1.25, 1.75), (1.75, 1.75), (1.75, 1.25)]), ], crs=CRS, )
Example #19
Source File: test_holes.py From maup with MIT License | 5 votes |
def test_removes_overlaps(self): # 00x11 # 00x11 # 00x11 square1 = square_at((0, 0), side_length=3) square2 = square_at((2, 0), side_length=3) geometries = geopandas.GeoSeries([square1, square2]) result = resolve_overlaps(geometries, relative_threshold=None) inters = adjacencies(result) assert not (inters.area > 0).any()
Example #20
Source File: test_intersections.py From maup with MIT License | 5 votes |
def test_works_with_non_range_index(self, sources, targets_with_str_index): result = intersections(sources, targets_with_str_index) assert isinstance(result, geopandas.GeoSeries) assert isinstance(result.index, pandas.MultiIndex)
Example #21
Source File: test_holes.py From maup with MIT License | 5 votes |
def test_raises_error_if_targets_empty(self): square1 = square_at((0, 0)) square2 = square_at((1, 0)) sources = geopandas.GeoSeries([square1, square2]) targets = geopandas.GeoSeries() with pytest.raises(IndexError): absorb_by_shared_perimeter(sources, targets)
Example #22
Source File: repair.py From maup with MIT License | 5 votes |
def absorb_by_shared_perimeter(sources, targets, relative_threshold=None): if len(sources) == 0: return targets if len(targets) == 0: raise IndexError("targets must be nonempty") inters = intersections(sources, targets, area_cutoff=None).buffer(0) assignment = assign_to_max(inters.length) if relative_threshold is not None: under_threshold = ( sources.area / assignment.map(targets.area) ) < relative_threshold assignment = assignment[under_threshold] sources_to_absorb = GeoSeries( sources.groupby(assignment).apply(unary_union), crs=sources.crs, ) result = targets.union(sources_to_absorb) # The .union call only returns the targets who had a corresponding # source to absorb. Now we fill in all of the unchanged targets. result = result.reindex(targets.index) did_not_absorb = result.isna() | result.is_empty result.loc[did_not_absorb] = targets[did_not_absorb] return result
Example #23
Source File: toolkit.py From peartree with MIT License | 5 votes |
def reproject(G: nx.MultiDiGraph, to_epsg: int=2163) -> nx.MultiDiGraph: # Avoid upstream mutation of the graph G = G.copy() # First extract current crs orig_crs = G.graph['crs'] # And get the array of nodes from original graph ref_node_array = list(G.nodes(data=True)) all_pts = [] for i, node in ref_node_array: all_pts.append(Point(node['x'], node['y'])) # Convert the collected nodes to GeoSeries gs = gpd.GeoSeries(all_pts) # And then reproject from original crs to new gs.crs = orig_crs gs = gs.to_crs(epsg=to_epsg) # Now iterate back through the reprojected points # and add each to it's respected node for (i, node), new_pt in zip(ref_node_array, gs): G.nodes[i]['x'] = new_pt.x G.nodes[i]['y'] = new_pt.y # Update the graph's coordinate reference G.graph['crs'] = {'init': 'epsg:{}'.format(to_epsg)} # Return the reprojected copy return G
Example #24
Source File: test_types.py From cate with MIT License | 5 votes |
def test_compat_with_geopandas(self): features = read_test_features() gdf = GeoDataFrame.from_features(features) self.assertIs(type(gdf), GeoDataFrame) self.assertIsInstance(gdf, GeoDataFrame) self.assertIsInstance(gdf, gpd.GeoDataFrame) self.assertIsInstance(gdf, pd.DataFrame) self.assertIs(gdf.features, features) self.assertIsInstance(gdf['A'], pd.Series) self.assertIsInstance(gdf.geometry, gpd.GeoSeries)
Example #25
Source File: conftest.py From maup with MIT License | 5 votes |
def big_square(): return gp.GeoSeries([Polygon([(0, 0), (2, 0), (2, 2), (0, 2)])], crs=CRS)
Example #26
Source File: test_holes.py From maup with MIT License | 5 votes |
def test_closes_gaps(self): # 001 # 0 1 # 001 pacman = Polygon( [(0, 0), (0, 3), (2, 3), (2, 2), (1, 2), (1, 1), (2, 1), (2, 0)] ) bar = Polygon([(2, 0), (2, 3), (3, 3), (3, 0)]) geometries = geopandas.GeoSeries([pacman, bar]) fixed = close_gaps(geometries, relative_threshold=None) assert fixed[1].equals(bar) assert fixed[0].equals(Polygon([(0, 0), (0, 3), (2, 3), (2, 0)]))
Example #27
Source File: test_holes.py From maup with MIT License | 5 votes |
def test_raises_for_non_polygons(self): has_a_point = geopandas.GeoSeries([Point((0, 0)), square_at((0, 0))]) with pytest.raises(TypeError): holes_of_union(has_a_point)
Example #28
Source File: test_holes.py From maup with MIT License | 5 votes |
def test_single_geometry(self): hole_coords = [(25, 25), (75, 25), (75, 75), (25, 75)] geometry = Polygon( [(0, 0), (100, 0), (100, 100), (0, 100)], holes=[hole_coords] ) result = holes_of_union(geopandas.GeoSeries([geometry])) assert len(result) == 1 assert result[0] == Polygon(hole_coords)
Example #29
Source File: adjacencies.py From maup with MIT License | 5 votes |
def adjacencies( geometries, adjacency_type="rook", *, warn_for_overlaps=True, warn_for_islands=True ): """Returns adjacencies between geometries. The return type is a `GeoSeries` with a `MultiIndex`, whose (i, j)th entry is the pairwise intersection between geometry `i` and geometry `j`. We ensure that `i < j` always holds, so that any adjacency is represented just once in the series. """ if adjacency_type not in ["rook", "queen"]: raise ValueError('adjacency_type must be "rook" or "queen"') index, geoms = zip(*iter_adjacencies(geometries)) inters = GeoSeries(geoms, index=index, crs=geometries.crs) if adjacency_type == "rook": inters = inters[inters.length > 0] if warn_for_overlaps: overlaps = inters[inters.area > 0] if len(overlaps) > 0: warnings.warn( "Found overlapping polygons while computing adjacencies.\n" "This could be evidence of topological problems.\n" "Indices of overlaps: {}".format(set(overlaps.index)), OverlapWarning, ) if warn_for_islands: islands = set(geometries.index) - set(i for pair in inters.index for i in pair) if len(islands) > 0: warnings.warn( "Found islands.\n" "Indices of islands: {}".format(islands), IslandWarning, ) return inters
Example #30
Source File: test_types.py From cate with MIT License | 5 votes |
def test_cate_cdm_type_names(self): """ Cate Common Data Model (CDM) types """ self.assertEqual(object_to_qualified_name(np.ndarray), 'numpy.ndarray') self.assertEqual(object_to_qualified_name(xr.Dataset), 'xarray.core.dataset.Dataset') self.assertEqual(object_to_qualified_name(xr.DataArray), 'xarray.core.dataarray.DataArray') self.assertEqual(object_to_qualified_name(gpd.GeoDataFrame), 'geopandas.geodataframe.GeoDataFrame') self.assertEqual(object_to_qualified_name(gpd.GeoSeries), 'geopandas.geoseries.GeoSeries') self.assertEqual(object_to_qualified_name(pd.DataFrame), 'pandas.core.frame.DataFrame') self.assertEqual(object_to_qualified_name(pd.Series), 'pandas.core.series.Series')