本文整理汇总了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'])
示例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)
示例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)
示例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)
示例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
#######################################################################
示例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')
示例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')
示例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")
示例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
示例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
示例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
示例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
示例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
示例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
示例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)