当前位置: 首页>>代码示例>>Python>>正文


Python geopandas.read_file方法代码示例

本文整理汇总了Python中geopandas.read_file方法的典型用法代码示例。如果您正苦于以下问题:Python geopandas.read_file方法的具体用法?Python geopandas.read_file怎么用?Python geopandas.read_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在geopandas的用法示例。


在下文中一共展示了geopandas.read_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_inventory

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [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

示例2: ogr2snwe

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def ogr2snwe(vectorFile, buffer=None):
    """Convert ogr shape to South,North,West,East bounds.

    Parameters
    ----------
    vectorFile : str
        path to OGR-recognized vector file.
    buffer : float
        Amount of buffer distance to add to shape (in decimal degrees).

    Returns
    -------
    snwe :  list
        a list of coorinate bounds [S, N, W, E]

    """
    gf = gpd.read_file(vectorFile)
    gf.to_crs(epsg=4326, inplace=True)
    poly = gf.geometry.convex_hull
    if buffer:
        poly = poly.buffer(buffer)
    W, S, E, N = poly.bounds.values[0]
    snwe = [S, N, W, E]

    return snwe 
开发者ID:scottyhq,项目名称:dinosar,代码行数:27,代码来源:__init__.py

示例3: setup_method

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def setup_method(self):

        test_file_path = mm.datasets.get_path("bubenec")
        self.df_buildings = gpd.read_file(test_file_path, layer="buildings")
        self.df_streets = gpd.read_file(test_file_path, layer="streets")
        self.df_tessellation = gpd.read_file(test_file_path, layer="tessellation")
        self.df_streets["nID"] = mm.unique_id(self.df_streets)
        self.df_buildings["height"] = np.linspace(10.0, 30.0, 144)
        self.df_tessellation["area"] = self.df_tessellation.geometry.area
        self.df_buildings["area"] = self.df_buildings.geometry.area
        self.df_buildings["fl_area"] = mm.FloorArea(self.df_buildings, "height").series
        self.df_buildings["nID"] = mm.get_network_id(
            self.df_buildings, self.df_streets, "nID"
        )
        blocks = mm.Blocks(
            self.df_tessellation, self.df_streets, self.df_buildings, "bID", "uID"
        )
        self.blocks = blocks.blocks
        self.df_buildings["bID"] = blocks.buildings_id
        self.df_tessellation["bID"] = blocks.tessellation_id 
开发者ID:martinfleis,项目名称:momepy,代码行数:22,代码来源:test_intensity.py

示例4: test_network_false_nodes

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [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

示例5: _read_shapefile_from_path

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def _read_shapefile_from_path(cls, fp):
        if '.shp' not in fp:
            raise ValueError('File ending not that of a shapefile')

        if cfg.PARAMS['use_tar_shapefiles']:
            fp = 'tar://' + fp.replace('.shp', '.tar')
            if cfg.PARAMS['use_compression']:
                fp += '.gz'

        shp = gpd.read_file(fp)

        # .properties file is created for compressed shapefiles. github: #904
        _properties = fp.replace('tar://', '') + '.properties'
        if os.path.isfile(_properties):
            # remove it, to keep GDir slim
            os.remove(_properties)

        return shp 
开发者ID:OGGM,项目名称:oggm,代码行数:20,代码来源:_workflow.py

示例6: inversion_gdir

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def inversion_gdir(class_case_dir):
    from oggm import GlacierDirectory
    from oggm.tasks import define_glacier_region
    import geopandas as gpd

    # Init
    cfg.initialize()
    cfg.set_intersects_db(get_demo_file('rgi_intersect_oetztal.shp'))
    cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
    cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')

    hef_file = get_demo_file('Hintereisferner_RGI5.shp')
    entity = gpd.read_file(hef_file).iloc[0]

    gdir = GlacierDirectory(entity, base_dir=class_case_dir, reset=True)
    define_glacier_region(gdir)
    return gdir 
开发者ID:OGGM,项目名称:oggm,代码行数:19,代码来源:test_models.py

示例7: get_thermal_network_from_shapefile

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def get_thermal_network_from_shapefile(locator, network_type, network_name):
    """
    This function reads the existing node and pipe network from a shapefile and produces an edge-node incidence matrix
    (as defined by Oppelt et al., 2016) as well as the edge properties (length, start node, and end node) and node
    coordinates.
    """

    # import shapefiles containing the network's edges and nodes
    network_edges_df = gpd.read_file(locator.get_network_layout_edges_shapefile(network_type, network_name))
    network_nodes_df = gpd.read_file(locator.get_network_layout_nodes_shapefile(network_type, network_name))

    # check duplicated NODE/PIPE IDs
    duplicated_nodes = network_nodes_df[network_nodes_df.Name.duplicated(keep=False)]
    duplicated_edges = network_edges_df[network_edges_df.Name.duplicated(keep=False)]
    if duplicated_nodes.size > 0:
        raise ValueError('There are duplicated NODE IDs:', duplicated_nodes)
    if duplicated_edges.size > 0:
        raise ValueError('There are duplicated PIPE IDs:', duplicated_nodes)

    # get node and pipe information
    node_df, edge_df = extract_network_from_shapefile(network_edges_df, network_nodes_df)

    return edge_df, node_df 
开发者ID:architecture-building-systems,项目名称:CityEnergyAnalyst,代码行数:25,代码来源:simplified_thermal_network.py

示例8: read

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def read(self, epsg=None, **kwargs):
        """
        Read vector data from Girder
        :param format: Format to return data in (default is GeoDataFrame)
        :param epsg: EPSG code to reproject data to
        :return: Data in GeoJSON
        """

        if self.data is None:
            self.save_geojson()
            self.data = geopandas.read_file(self.uri)
            if self.filters:
                self.filter_data()
        out_data = self.data
        if epsg and self.get_epsg() != epsg:
            out_data = geopandas.GeoDataFrame.copy(out_data)
            out_data[out_data.geometry.name] = \
                self.data.geometry.to_crs(epsg=epsg)
            out_data.crs = fiona.crs.from_epsg(epsg)
        if format == formats.JSON:
            return out_data.to_json()
        else:
            return out_data 
开发者ID:Kitware,项目名称:minerva,代码行数:25,代码来源:inputs.py

示例9: test_classification

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def test_classification(self):
        training_pt = gpd.read_file(nc.points)

        df_points = self.stack_nc.extract_vector(gdf=training_pt)
        df_points["class_id"] = training_pt["id"]
        df_points = df_points.dropna()

        clf = RandomForestClassifier(n_estimators=50)
        X = df_points.drop(columns=["id", "class_id", "geometry"])
        y = df_points.class_id
        clf.fit(X, y)

        # classification
        cla = self.stack_nc.predict(estimator=clf, dtype="int16", nodata=0)
        self.assertIsInstance(cla, Raster)
        self.assertEqual(cla.count, 1)
        self.assertEqual(cla.read(masked=True).count(), 135092)

        # class probabilities
        probs = self.stack_nc.predict_proba(estimator=clf)
        self.assertIsInstance(cla, Raster)
        self.assertEqual(probs.count, 7)

        for _, layer in probs:
            self.assertEqual(layer.read(masked=True).count(), 135092) 
开发者ID:stevenpawley,项目名称:Pyspatialml,代码行数:27,代码来源:test_prediction.py

示例10: test_regression

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def test_regression(self):
        training_pt = gpd.read_file(ms.meuse)
        training = self.stack_meuse.extract_vector(gdf=training_pt)
        training["zinc"] = training_pt["zinc"]
        training["cadmium"] = training_pt["cadmium"]
        training["copper"] = training_pt["copper"]
        training["lead"] = training_pt["lead"]
        training = training.dropna()

        # single target regression
        regr = RandomForestRegressor(n_estimators=50)
        X = training.loc[:, self.stack_meuse.names]
        y = training["zinc"]
        regr.fit(X, y)

        single_regr = self.stack_meuse.predict(regr)
        self.assertIsInstance(single_regr, Raster)
        self.assertEqual(single_regr.count, 1)

        # multi-target regression
        y = training.loc[:, ["zinc", "cadmium", "copper", "lead"]]
        regr.fit(X, y)
        multi_regr = self.stack_meuse.predict(regr)
        self.assertIsInstance(multi_regr, Raster)
        self.assertEqual(multi_regr.count, 4) 
开发者ID:stevenpawley,项目名称:Pyspatialml,代码行数:27,代码来源:test_prediction.py

示例11: test_extract_points

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def test_extract_points(self):
        training_pt = geopandas.read_file(nc.points)

        # check that extracted training data as array match known values
        ids, X, xys = self.stack.extract_vector(gdf=training_pt, return_array=True)
        
        self.assertTrue((X[~X[:, 0].mask, 0].data == training_pt["b1"].dropna().values).all())
        self.assertTrue((X[~X[:, 1].mask, 1].data == training_pt["b2"].dropna().values).all())
        self.assertTrue((X[~X[:, 2].mask, 2].data == training_pt["b3"].dropna().values).all())
        self.assertTrue((X[~X[:, 3].mask, 3].data == training_pt["b4"].dropna().values).all())
        self.assertTrue((X[~X[:, 4].mask, 4].data == training_pt["b5"].dropna().values).all())
        self.assertTrue((X[~X[:, 5].mask, 5].data == training_pt["b7"].dropna().values).all())

        # check that extracted training data as a DataFrame match known values
        df = self.stack.extract_vector(gdf=training_pt)
        
        self.assertTrue(df["lsat7_2000_10"].equals(training_pt["b1"]))
        self.assertTrue(df["lsat7_2000_20"].equals(training_pt["b2"]))
        self.assertTrue(df["lsat7_2000_30"].equals(training_pt["b3"]))
        self.assertTrue(df["lsat7_2000_40"].equals(training_pt["b4"]))
        self.assertTrue(df["lsat7_2000_50"].equals(training_pt["b5"]))
        self.assertTrue(df["lsat7_2000_70"].equals(training_pt["b7"])) 
开发者ID:stevenpawley,项目名称:Pyspatialml,代码行数:24,代码来源:test_extract.py

示例12: test_extract_polygons

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def test_extract_polygons(self):        
        # extract training data from polygons
        training_py = geopandas.read_file(nc.polygons)
        df = self.stack.extract_vector(gdf=training_py)
        df = df.dropna()
        
        df = (
            df.merge(training_py.loc[:, ("id", "label")], left_on="id", right_index=True).
            drop(columns=["id_x"])
        )
        
        # compare to extracted data using GRASS GIS
        self.assertEqual(df.shape[0], self.extracted_grass.shape[0])
        self.assertAlmostEqual(df["lsat7_2000_10"].mean(), self.extracted_grass["b1"].mean(), places=3)
        self.assertAlmostEqual(df["lsat7_2000_20"].mean(), self.extracted_grass["b2"].mean(), places=3)
        self.assertAlmostEqual(df["lsat7_2000_30"].mean(), self.extracted_grass["b3"].mean(), places=3)
        self.assertAlmostEqual(df["lsat7_2000_40"].mean(), self.extracted_grass["b4"].mean(), places=3)
        self.assertAlmostEqual(df["lsat7_2000_50"].mean(), self.extracted_grass["b5"].mean(), places=3)
        self.assertAlmostEqual(df["lsat7_2000_70"].mean(), self.extracted_grass["b7"].mean(), places=3) 
开发者ID:stevenpawley,项目名称:Pyspatialml,代码行数:21,代码来源:test_extract.py

示例13: __load_country_shapes__

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def __load_country_shapes__():
    '''Load country shapes'''
    logger.info('Loading country shapes')
    # load shapefile for country shapes and get records
    world = geopandas.read_file(
        geopandas.datasets.get_path('naturalearth_lowres'))

    for _, country in world.iterrows():
        # Try to find the alpha 3 country code in the iso3166.
        # Sometimes it is not set ( value '-99'). Then we try to match by name.
        country_codes = iso3166.countries_by_alpha3.get(
            country['iso_a3'],
            iso3166.countries_by_name.get(country['name'].upper())
        )

        # log warning if the country is not found.
        if not country_codes:
            logger.warning('Unable to find %s', country['name'])
            continue

        # Save geometry as wkt string with both alpha 2 and 3 code as key.
        shape = country['geometry']
        __country_shapes__[country_codes.alpha2] = shape
        __country_shapes__[country_codes.alpha3] = shape 
开发者ID:emissions-api,项目名称:emissions-api,代码行数:26,代码来源:country_shapes.py

示例14: vcount

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def vcount(shpfile):
    df = gp.read_file(shpfile)
    if not df.size==0:
        for i, row in df.iterrows():
            # It's better to check if multigeometry
            multi = row.geometry.type.startswith("Multi")
            if multi:
                n = 0
                # iterate over all parts of multigeometry
                for part in row.geometry:
                    n += len(part.exterior.coords)
            else: # if single geometry like point, linestring or polygon
                n = len(row.geometry.exterior.coords)

            #print('Total vertices: {:,}'.format(n))
            overall.append(n)
        if all(i < 1000000 for i in overall)==True:
            return sum(overall)
        else:
            logger.warning(shpfile+' has overall max vertex of '+str(max(overall))+' with max allowed 1000000 ingest might fail')
            return sum(overall)
            #print('Total vertices per feature exceeded max. Overall vertices: {}'.format(sum(overall)))
            #return sum(overall)
    else:
        return df.size 
开发者ID:samapriya,项目名称:geeup,代码行数:27,代码来源:zipfiles.py

示例15: transects_from_geojson

# 需要导入模块: import geopandas [as 别名]
# 或者: from geopandas import read_file [as 别名]
def transects_from_geojson(filename):
    """
    Reads transect coordinates from a .geojson file.
    
    Arguments:
    -----------
    filename: str
        contains the path and filename of the geojson file to be loaded
        
    Returns:    
    -----------
    transects: dict
        contains the X and Y coordinates of each transect
        
    """  
    
    gdf = gpd.read_file(filename)
    transects = dict([])
    for i in gdf.index:
        transects[gdf.loc[i,'name']] = np.array(gdf.loc[i,'geometry'].coords)
        
    print('%d transects have been loaded' % len(transects.keys()))

    return transects 
开发者ID:kvos,项目名称:CoastSat,代码行数:26,代码来源:SDS_tools.py


注:本文中的geopandas.read_file方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。