How to use the geopandas.GeoDataFrame function in geopandas

To help you get started, we’ve selected a few geopandas examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CCI-Tools / cate / tests / core / test_workspace.py View on Github external
def scalar_geo_data_frame_op() -> gpd.GeoDataFrame:
            data = {'name': [2000 * 'A'],
                    'lat': [45],
                    'lon': [-120]}
            df = pd.DataFrame(data, columns=['name', 'lat', 'lon'])
            geometry = [Point(xy) for xy in zip(df['lon'], df['lat'])]
            return gpd.GeoDataFrame(df, geometry=geometry)
github Servir-Mekong / hydra-floods / hydrafloods / hfcli.py View on Github external
raise AttributeError('provided yaml file does not have a name parameter in configuration')

            if 'region' in confKeys:
                self.region = gpd.read_file(conf['region'])

            elif 'country' in confKeys:
                world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
                country = world[world.name == conf['country']]
                if len(country) >= 1:
                    self.region = country
                else:
                    raise ValueError('could not parse selected country from world shapefile')

            elif 'boundingbox' in confKeys:
                from shapely import geometry
                self.region = gpd.GeoDataFrame(pd.DataFrame({'id':[0],'geometry':[geometry.box(*conf['boundingbox'])]}))

            else:
                raise AttributeError('provided yaml file does not have a specified region in configuration')

            if 'credentials' in confKeys:
                self.credentials = conf['credentials']
            else:
                self.credentials = None

            if 'stagingBucket' in confKeys:
                self.stagingBucket = conf['stagingBucket']
            else:
                self.stagingBucket = None

            if 'targetAsset' in confKeys:
                self.targetAsset = conf['targetAsset']
github geopandas / geopandas / geopandas / io / sql.py View on Github external
load_geom = load_geom_buffer
            else:
                load_geom = load_geom_text
        elif isinstance(geoms.iat[0], bytes):
            load_geom = load_geom_bytes
        else:
            load_geom = load_geom_text

        df[geom_col] = geoms = geoms.apply(load_geom)
        if crs is None:
            srid = shapely.geos.lgeos.GEOSGetSRID(geoms.iat[0]._geom)
            # if no defined SRID in geodatabase, returns SRID of 0
            if srid != 0:
                crs = {"init": "epsg:{}".format(srid)}

    return GeoDataFrame(df, crs=crs, geometry=geom_col)
github pyviz-topics / EarthSim / earthsim / annotators.py View on Github external
Parameters
    ----------

    polys : gv.Path or gv.Polygons
        GeoViews element
    columns: list(str)
        List of columns

    Returns
    -------
    gdf : Geopandas dataframe
    """
    rows = []
    for g in polys.geom():
        rows.append(dict({c: '' for c in columns}, geometry=g))
    return gpd.GeoDataFrame(rows, columns=columns+['geometry'])
github SpaceNetChallenge / utilities / spacenetutilities / osmtools / coreosmtools.py View on Github external
edgesList.append(tmpElement)

    gdf_nodes = gpd.GeoDataFrame(nodesList)
    edgesList2 = []
    for edge in edgesList:
        gdflist = gdf_nodes['id'].map(lambda x: x in edge['nodes'])
        print(len(edge))
        print(edge)
        if edge['nodes'][0] == edge['nodes'][-1]:
            edge.update({'geometry': Polygon(LineString(list(gdf_nodes[gdflist].geometry.values)))
                         })
        else:
            edge.update({'geometry': LineString(list(gdf_nodes[gdflist].geometry.values))
                     })
        edgesList2.append(edge)
    gdf_edges = gpd.GeoDataFrame(edgesList2)

    return gdf_edges, gdf_nodes
github mathieuripert / geoh / geoh / geoh.py View on Github external
def geohashes_polygon_intersection(polygon, geohashes=[]):
  df = gpd.GeoDataFrame(geohashes, columns=["geohash"])
  df["geometry"] = df.apply(lambda x: _geohash_to_shape(x["geohash"]), axis=1)
  return list(df[df.intersects(polygon)].geohash)
github FZJ-IEK3-VSA / FINE / FINE / expansionModules / robustPipelineSizing.py View on Github external
newLines_.append(shp.geometry.LineString([newNode,nodeEnd]))
            newLinesName_.append('temp')
            nodesIn_.append(newNodeName), nodesOut_.append(row['nodeOut'])
            
            newNodes.extend(newNodes_), newLines.extend(newLines_), newNodesName.extend(newNodesName_)
            newLinesName.extend(newLinesName_), pMin.extend(pMin_), pMax.extend(pMax_)
            nodesIn.extend(nodesIn_), nodesOut.extend(nodesOut_), coords.extend(coords_)   

    if len(newNodes) > 0:
        dfNodes = dfNodes.append(pd.DataFrame([newNodesName, pMin, pMax, coords],
                                            index=['nodeName','pMin','pMax','lon_lat']).T)

        dfEdges = pd.DataFrame([nodesIn, nodesOut, newLinesName, newLines],
                            index=['nodeIn', 'nodeOut','edgeName','geometry']).T
        gdfEdgesNew = gpd.GeoDataFrame(dfEdges,crs=gdf.crs).to_crs({'init': 'epsg:3035'})
        gdfEdges = gdfEdges.append(gdfEdgesNew)
        gdfEdges = gdfEdges[gdfEdges.geometry.length.round(2) <= maxPipeLength]

    del gdfEdges['edgeName']

    renameDict = {name: 'auxNode' + str(i) for i, name in enumerate(dfNodes.nodeName.values)
                if name not in originalNodesSet}

    for node in originalNodesSet:
        renameDict.update({node:node})

    gdfEdges['nodeIn'] = gdfEdges.apply(lambda x: renameDict[x['nodeIn']], axis=1)
    gdfEdges['nodeOut'] = gdfEdges.apply(lambda x: renameDict[x['nodeOut']], axis=1)

    gdfEdges['distances'] = gdfEdges['geometry'].length
github mthh / gpd_lite_toolbox / gpd_lite_toolbox / utils.py View on Github external
for i in range(len(self.result)):
            fti = self.result.iloc[i]
            for j in self._filt(fti):
                try:
                    puidj = str(round(j.geometry.length, -2))
                    if j['FRONT'] + puidj not in seen \
                            and j['FRONT_r'] + puidj not in seen:
                        key1 = j['FRONT'] + puidj
                        key2 = j['FRONT_r'] + puidj
                        seen[key1] = 1
                        seen[key2] = 1
                        self.border.append(j)
                except TypeError as err:
                    print(err)
                    pass
        self.border = gpd.GeoDataFrame(self.border)
#        print('{:.2f}s'.format(time.time()-s_t))
github wannesm / LeuvenMapMatching / leuvenmapmatching / map / gdfmap.py View on Github external
def prepare_index(self, force=False):
        if self.nodes is not None and not force:
            return

        if self.use_latlon:
            lats, lons, labels = [], [], []
            for label, data in self.graph.items():
                labels.append(label)
                lats.append(data[0][0])
                lons.append(data[0][1])
            df = pd.DataFrame({'label': labels, 'lat': lats, 'lon': lons})
            df['Coordinates'] = list(zip(df.lon, df.lat))
            df['Coordinates'] = df['Coordinates'].apply(Point)
            self.nodes = gp.GeoDataFrame(df, geometry='Coordinates', crs=self.crs_in)

        else:
            ys, xs, labels = [], [], []
            for label, data in self.graph.items():
                labels.append(label)
                ys.append(data[0][0])
                xs.append(data[0][1])
            df = pd.DataFrame({'label': labels, 'y': ys, 'x': xs})
            df['Coordinates'] = list(zip(df.x, df.y))
            df['Coordinates'] = df['Coordinates'].apply(Point)
            self.nodes = gp.GeoDataFrame(df, geometry='Coordinates', crs=self.crs_in)
github spatialucr / geosnap / geosnap / data / data.py View on Github external
df = _fips_filter(
        state_fips=state_fips,
        county_fips=county_fips,
        msa_fips=msa_fips,
        fips=fips,
        data=data,
    )

    # we know we're using 2010, need to drop the year column so no conficts
    tracts = data_store.tracts_2010(convert=False)
    tracts = tracts[["geoid", "wkb"]]
    tracts = tracts[tracts.geoid.isin(df.geoid)]
    tracts = convert_gdf(tracts)

    gdf = df.merge(tracts, on="geoid", how="left").set_index("geoid")
    gdf = gpd.GeoDataFrame(gdf)
    return gdf