从 Azure 机器学习中的 Azure Blob 存储读取 shapefile

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

我在 Azure 机器学习工作区的 Azure Blob 存储中存储了多个 shapefile,每个 shapefile 都包含以下文件:file.fix、file.shp、file.dbf、file.prj 和 file.shx。我需要在我的 Azure 机器学习环境中直接访问和读取这些 shapefile。

到目前为止,我已经使用以下代码成功读取了 Parquet 文件:

Dataset.Tabular.from_parquet_files(path=[(datastore, file_path)]).to_pandas_dataframe()

和 CSV 文件使用:

table = Dataset.Tabular.from_delimited_files(path=[(datastore, file_path)]).to_pandas_dataframe()

虽然我确实遇到了在 Azure Databricks 中读取 shapefile 的解决方案,但我还没有找到在 Azure 机器学习中完成此操作的直接方法。

我知道一种解决方法可能是下载文件并在代码中本地读取它们。但是,我不确定这种方法的实现细节。

任何帮助将不胜感激。

shapefile azure-machine-learning-service azureml-python-sdk azuremlsdk azure-ml-component
1个回答
0
投票

您可以按照以下方法进行操作。

下载所有必需文件的代码:

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

def download_blob_folder(blob_service_client, container_name, folder_name, local_directory):
    container_client = blob_service_client.get_container_client(container_name)
    blobs_list = container_client.list_blobs(name_starts_with=folder_name)

    for blob in blobs_list:
        blob_client = container_client.get_blob_client(blob)
        blob_relative_path = blob.name[len(folder_name)+1:]
        local_file_path = os.path.join(local_directory, blob_relative_path)

        os.makedirs(os.path.dirname(local_file_path), exist_ok=True)

        with open(local_file_path, "wb") as file:
            download_stream = blob_client.download_blob()
            file.write(download_stream.read())
        print(blob_relative_path,local_directory)
        print(f"Blob '{blob.name}' downloaded to '{local_file_path}'")


connection_string = "DefaultEndpointsProtocol=https;AccountName=venkat789;AccountKey=xxxxxxxxxxxxxxxsaaaaaaaaaaaaaaaaaaadddddddcore.windows.net"
container_name = "sample"
folder_name = "map"


blob_service_client = BlobServiceClient.from_connection_string(connection_string)


local_directory = "./downloaded_files/"

download_blob_folder(blob_service_client, container_name, folder_name, local_directory)

在这里,我正在下载从文件夹

map
读取 shapefile 所需的所有文件。确保该文件夹中只有需要读取的文件,因为上面的代码会下载给定文件夹中存在的所有文件。

下载后,通过pip安装geopandas:

pip install geopandas

要阅读的代码:

import geopandas as gpd

file_name="./downloaded_files/gadm41_IND_0.shp"
data = gpd.read_file(file_name)
data

输出:

enter image description here

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