當前位置: 首頁>>代碼示例>>Python>>正文


Python geopandas.GeoDataFrame方法代碼示例

本文整理匯總了Python中geopandas.GeoDataFrame方法的典型用法代碼示例。如果您正苦於以下問題:Python geopandas.GeoDataFrame方法的具體用法?Python geopandas.GeoDataFrame怎麽用?Python geopandas.GeoDataFrame使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在geopandas的用法示例。


在下文中一共展示了geopandas.GeoDataFrame方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: poly_to_geopandas

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def poly_to_geopandas(polys, columns):
    """
    Converts a GeoViews Paths or Polygons type to a geopandas dataframe.

    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']) 
開發者ID:pyviz-topics,項目名稱:EarthSim,代碼行數:22,代碼來源:annotators.py

示例2: buildings_from_point

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def buildings_from_point(date, point, distance, retain_invalid=False):
	"""
	Get building footprints within some distance north, south, east, and west of
	a lat-long point.
	Parameters
	----------
	date : string
		query the database at a certain timestamp
	point : tuple
		a lat-long point
	distance : numeric
		distance in meters
	retain_invalid : bool
		if False discard any building footprints with an invalid geometry
	Returns
	-------
	GeoDataFrame
	"""

	bbox = ox.bbox_from_point(point=point, distance=distance)
	north, south, east, west = bbox
	return create_buildings_gdf(date=date, north=north, south=south, east=east, west=west, retain_invalid=retain_invalid) 
開發者ID:lgervasoni,項目名稱:urbansprawl,代碼行數:24,代碼來源:overpass.py

示例3: buildings_from_address

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def buildings_from_address(date, address, distance, retain_invalid=False):
	"""
	Get building footprints within some distance north, south, east, and west of
	an address.
	Parameters
	----------
	date : string
		query the database at a certain timestamp
	address : string
		the address to geocode to a lat-long point
	distance : numeric
		distance in meters
	retain_invalid : bool
		if False discard any building footprints with an invalid geometry
	Returns
	-------
	GeoDataFrame
	"""

	# geocode the address string to a (lat, lon) point
	point = ox.geocode(query=address)

	# get buildings within distance of this point
	return buildings_from_point(date, point, distance, retain_invalid=retain_invalid) 
開發者ID:lgervasoni,項目名稱:urbansprawl,代碼行數:26,代碼來源:overpass.py

示例4: buildings_from_polygon

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def buildings_from_polygon(date, polygon, retain_invalid=False):
	"""
	Get building footprints within some polygon.
	Parameters
	----------
	date : string
		query the database at a certain timestamp
	polygon : Polygon
	retain_invalid : bool
		if False discard any building footprints with an invalid geometry
	Returns
	-------
	GeoDataFrame
	"""

	return create_buildings_gdf(date=date, polygon=polygon, retain_invalid=retain_invalid) 
開發者ID:lgervasoni,項目名稱:urbansprawl,代碼行數:18,代碼來源:overpass.py

示例5: buildings_from_place

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def buildings_from_place(date, place, which_result=1, retain_invalid=False):
	"""
	Get building footprints within the boundaries of some place.
	Parameters
	----------
	date : string
		query the database at a certain timestamp
	place : string
		the query to geocode to get geojson boundary polygon
	which_result : int
		result number to retrieve from geocode/download when using query string 
	retain_invalid : bool
		if False discard any building footprints with an invalid geometry
	Returns
	-------
	GeoDataFrame
	"""
	city = ox.gdf_from_place(place, which_result=which_result)
	polygon = city['geometry'].iloc[0]
	return create_buildings_gdf(date=date, polygon=polygon, retain_invalid=retain_invalid)

#######################################################################
### Street network graph
####################################################################### 
開發者ID:lgervasoni,項目名稱:urbansprawl,代碼行數:26,代碼來源:overpass.py

示例6: WriteHillslopeTracesShp

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def WriteHillslopeTracesShp(DataDirectory,FilenamePrefix):
    """
    This function writes a shapefile of hillslope traces

    Args:
        DataDirectory: the data directory
        FilenamePrefix: the file name prefix

    Author: MDH
    """
    
    #read the raw data to geodataframe
    geo_df = ReadHillslopeTraces(DataDirectory,FilenamePrefix)
    Suffix = '_hillslope_traces'
    WriteFilename = DataDirectory+FilenamePrefix+Suffix+'.shp'
    
    #aggregate these points with group by
    geo_df = geo_df.groupby(['HilltopID'])['geometry'].apply(lambda x: LineString(x.tolist()))
    geo_df = GeoDataFrame(geo_df, geometry='geometry')
    geo_df.to_file(WriteFilename, driver='ESRI Shapefile') 
開發者ID:LSDtopotools,項目名稱:LSDMappingTools,代碼行數:22,代碼來源:plot_hillslope_morphology.py

示例7: WriteHillslopeTracesShp

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def WriteHillslopeTracesShp(DataDirectory,FilenamePrefix,ThinningFactor=1, CustomExtent=[-9999]):
    """
    This function writes a shapefile of hillslope traces

    Args:
        DataDirectory: the data directory
        FilenamePrefix: the file name prefix
        ThinningFactor (int): This determines how many of the traces are discarded. Higher numbers mean more traces are discarded
        CustomExtent (list): if this is [-9999] the extent is grabbed from the raster. Otherwise you give it a 4 element list giving the extent of the area of interest.

    Returns: None, but writes a shapefile

    Author: MDH
    """

    #read the raw data to geodataframe
    geo_df = ReadHillslopeTraces(DataDirectory,FilenamePrefix,ThinningFactor, CustomExtent)
    Suffix = '_hillslope_traces'
    WriteFilename = DataDirectory+FilenamePrefix+Suffix+'.shp'

    #aggregate these points with group by
    geo_df = geo_df.groupby(['HilltopID'])['geometry'].apply(lambda x: LineString(x.tolist()))
    geo_df = GeoDataFrame(geo_df, geometry='geometry')
    geo_df.to_file(WriteFilename, driver='ESRI Shapefile') 
開發者ID:LSDtopotools,項目名稱:LSDMappingTools,代碼行數:26,代碼來源:LSDMap_HillslopeMorphology.py

示例8: save_geojson_footprints

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def save_geojson_footprints(gf):
    """Save all frames from each date as separate geojson file.

    JSON footprints with metadata are easily visualized if pushed to GitHub.
    This saves a bunch of [date].geojson files in local directory.

    Parameters
    ----------
    gf : GeoDataFrame
        a pandas geodataframe from load_asf_json

    """
    attributes = ("granuleName", "downloadUrl", "geometry")
    gb = gf.groupby(["relativeOrbit", "sceneDateString"])
    S = gf.groupby("relativeOrbit").sceneDateString.unique()
    for orbit, dateList in S.iteritems():
        os.makedirs(str(orbit))
        for date in dateList:
            dftmp = gf.loc[gb.groups[(orbit, date)], attributes].reset_index(drop=True)
            outname = f"{orbit}/{date}.geojson"
            dftmp.to_file(outname, driver="GeoJSON") 
開發者ID:scottyhq,項目名稱:dinosar,代碼行數:23,代碼來源:__init__.py

示例9: load_inventory

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def load_inventory(inventoryJSON):
    """Load inventory saved with asf.archive.save_inventory().

    Parameters
    ----------
    inventoryJSON : str
        dinsar inventory file (query.geojson)

    Returns
    -------
    gf :  GeoDataFrame
        A geopandas GeoDataFrame

    """
    gf = gpd.read_file(inventoryJSON)
    gf["timeStamp"] = pd.to_datetime(gf.sceneDate, format="%Y-%m-%d %H:%M:%S")
    gf["sceneDateString"] = gf.timeStamp.apply(lambda x: x.strftime("%Y-%m-%d"))
    gf["dateStamp"] = pd.to_datetime(gf.sceneDateString)
    gf["utc"] = gf.timeStamp.apply(lambda x: x.strftime("%H:%M:%S"))
    gf["relativeOrbit"] = gf.relativeOrbit.astype("int")
    gf.sort_values("relativeOrbit", inplace=True)
    gf["orbitCode"] = gf.relativeOrbit.astype("category").cat.codes

    return gf 
開發者ID:scottyhq,項目名稱:dinosar,代碼行數:26,代碼來源:__init__.py

示例10: to_geodataframe

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def to_geodataframe(self):
        """
        Convert to a GeoDataFrame.

        Returns
        -------
        :obj:`geopandas.GeoDataFrame`

        """
        self._validate_operation()
        out_obj = self._obj.drop("crs")
        extra_coords = list(set(list(out_obj.coords)) - {"geometry"})
        if extra_coords:
            out_obj = out_obj.copy().reset_coords(extra_coords)
        geodf = gpd.GeoDataFrame(out_obj.to_dataframe().reset_index())
        geodf.crs = self._obj.coords["crs"].attrs["crs_wkt"]
        return geodf 
開發者ID:corteva,項目名稱:geocube,代碼行數:19,代碼來源:vectorxarray.py

示例11: _maybe_to_geodataframe

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def _maybe_to_geodataframe(df, schema):
    """
    If the required libraries for geospatial support are installed, and if a
    geospatial column is present in the dataframe, convert it to a
    GeoDataFrame.
    """

    def to_shapely(row, name):
        return shape.to_shape(row[name]) if row[name] is not None else None

    if len(df) and geospatial_supported:
        geom_col = None
        for name, dtype in schema.items():
            if isinstance(dtype, dt.GeoSpatial):
                geom_col = geom_col or name
                df[name] = df.apply(lambda x: to_shapely(x, name), axis=1)
        if geom_col:
            df = geopandas.GeoDataFrame(df, geometry=geom_col)
    return df 
開發者ID:ibis-project,項目名稱:ibis,代碼行數:21,代碼來源:alchemy.py

示例12: unique_id

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def unique_id(objects):
    """
    Add an attribute with unique ID to each row of GeoDataFrame.

    Parameters
    ----------
    objects : GeoDataFrame
        GeoDataFrame containing objects to analyse

    Returns
    -------
    Series
        Series containing resulting values.

    """
    series = range(len(objects))
    return series 
開發者ID:martinfleis,項目名稱:momepy,代碼行數:19,代碼來源:utils.py

示例13: gdf_to_nx

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def gdf_to_nx(gdf_network, approach="primal", length="mm_len"):
    """
    Convert LineString GeoDataFrame to networkx.MultiGraph

    Parameters
    ----------
    gdf_network : GeoDataFrame
        GeoDataFrame containing objects to convert
    approach : str, default 'primal'
        Decide wheter genereate ``'primal'`` or ``'dual'`` graph.
    length : str, default mm_len
        name of attribute of segment length (geographical) which will be saved to graph

    Returns
    -------
    networkx.Graph
        Graph

    """
    gdf_network = gdf_network.copy()
    if "key" in gdf_network.columns:
        gdf_network.rename(columns={"key": "__key"}, inplace=True)
    # generate graph from GeoDataFrame of LineStrings
    net = nx.MultiGraph()
    net.graph["crs"] = gdf_network.crs
    gdf_network[length] = gdf_network.geometry.length
    fields = list(gdf_network.columns)

    if approach == "primal":
        _generate_primal(net, gdf_network, fields)

    elif approach == "dual":
        _generate_dual(net, gdf_network, fields)

    else:
        raise ValueError(
            "Approach {} is not supported. Use 'primal' or 'dual'.".format(approach)
        )

    return net 
開發者ID:martinfleis,項目名稱:momepy,代碼行數:42,代碼來源:utils.py

示例14: _lines_to_gdf

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
def _lines_to_gdf(net, lines, points, nodeID):
    """
    Generate linestring gdf from edges.
    Helper for nx_to_gdf.
    """
    starts, ends, edge_data = zip(*net.edges(data=True))
    if lines is True:
        node_start = []
        node_end = []
        for s in starts:
            node_start.append(net.nodes[s][nodeID])
        for e in ends:
            node_end.append(net.nodes[e][nodeID])
    gdf_edges = gpd.GeoDataFrame(list(edge_data))
    if points is True:
        gdf_edges["node_start"] = node_start
        gdf_edges["node_end"] = node_end
    if "crs" in net.graph.keys():
        gdf_edges.crs = net.graph["crs"]
    return gdf_edges 
開發者ID:martinfleis,項目名稱:momepy,代碼行數:22,代碼來源:utils.py

示例15: test_network_false_nodes

# 需要導入模塊: import geopandas [as 別名]
# 或者: from geopandas import GeoDataFrame [as 別名]
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) 
開發者ID:martinfleis,項目名稱:momepy,代碼行數:19,代碼來源:test_utils.py


注:本文中的geopandas.GeoDataFrame方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。