从 Azure Data Lake/Blob 容器读取 .shp 和 .shx 文件

问题描述 投票:0回答:1

我正在使用我们的 Azure 数据工厂从公共 api 加载 ZIP。然后,我使用复制活动解压缩该 ZIP,从而生成一堆 .shp/.shx 文件。

然后,我想使用 Python 脚本使用 geopandas 包将数据读入变量。为了实现这一点,我使用以下软件包:

azure-datalake-store

azure-存储-blob

import os
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

storage_conection_string = "myconnectionstring"
blob_service_client = BlobServiceClient.from_connection_string(storage_conection_string)


local_path = r"mypath"
local_file_name = "file.shp"

download_file_path = os.path.join(local_path, local_file_name)
container_client = blob_service_client.get_container_client(container= "mycontainer") 


with open(file=download_file_path, mode="wb") as download_file:
download_file.write(container_client.download_blob("fileonblobstorage").readall())

这会正确地将指定文件下载到我的本地存储。但是,我更愿意直接将其加载到地理数据集中,而不是将其保存在本地,然后再次读取。

这可以使用 .csv 文件,但 .shp 文件会返回引擎错误。由于它存储为二进制文件,我认为这是一个编码问题。但我似乎无法找到解决问题的方法。最后,我想谈谈这个:

import geopandas as gpd

gdf = gpd.read_file(container_client)

上面返回一个简单的错误,与我在 .csv 文件中得到的错误相同。但是,包装到 BytesIO 解决了将 .csv 文件转换为 pandas df 的问题,但在地理数据帧中返回 .shp 文件的引擎错误。

最后,为了正确加载,还必须加载 .shp 文件附带的 .shx 文件。当文件位于同一文件夹中时(blob 容器中也是如此),这通常由 geopandas 包自动完成。但是,第二个文件可能也需要解析。

python encoding azure-blob-storage geopandas shapefile
1个回答
0
投票

但是,我更愿意直接将其加载到地理数据集中,而不是保存在本地,然后再次读取

要从 Azure Blob 存储(私有容器)读取

.shp
文件而不将其保存在本地,您需要使用 Azure Databricks 环境。

首先,将存储帐户安装到 Databricks 并读取 shapefile (.shp)。

传送门: enter image description here

挂载代码:

dbutils.fs.mount(
source = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net",
mount_point = "/mnt/blob/",
extra_configs = {"fs.azure.account.key.<storage-account-name>.blob.core.windows.net":"<Account_key>"})

现在,您可以使用以下代码来读取Databricks中的形状文件:

代码:

gdf = geopandas.read_file("/dbfs/mnt/blob/map/gadm41_IND_0.shp")  #`dbfs` to path mountpoint+folder+filename
gdf

输出: enter image description here

或者,要从 Azure Blob 存储(公共容器)读取

.shp
文件而不将其保存在本地,可以使用以下代码:

代码:

import fiona
import geopandas as gpd

# Read the shapefile from the URL using fiona
url = "https://<Storage account name>.blob.core.windows.net/<container-name>/map/gadm41_IND_0.shp"
with fiona.open(url) as src:
    features = list(src)
gdf = gpd.GeoDataFrame.from_features(features)
print(gdf.head())

输出:

                                            geometry GID_0 COUNTRY
0  MULTIPOLYGON (((76.97542 8.38514, 76.97486 8.3...   IND   India
1  POLYGON ((75.07161 32.48296, 75.06268 32.48213...   Z01   India
2  POLYGON ((78.65135 32.09228, 78.65241 32.08826...   Z04   India
3  POLYGON ((80.08794 30.79071, 80.08796 30.79026...   Z05   India
4  POLYGON ((94.19125 27.49632, 94.18690 27.49081...   Z07   India

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.