You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中从HDFS读取Shapefile(.shp)文件?

在Python中从HDFS读取Shapefile的实现方法

Spark原生并不支持直接通过spark.read.format("shapefile")读取Shapefile,你可以通过以下两种方式实现需求:

方法一:通过HDFS客户端下载文件后用Geopandas读取

Shapefile是由.shp、.shx、.dbf等多个关联文件组成的,需要先将这些文件全部从HDFS下载到本地临时目录,再用Geopandas读取。

步骤:

  1. 安装依赖包:
pip install hdfs geopandas
  1. 实现代码:
from hdfs import InsecureClient
import geopandas as gpd
import tempfile
import os

# 连接HDFS
hdfs_client = InsecureClient('http://<namenode-ip>:<port>', user='<your-username>')

# HDFS上Shapefile所在的目录(注意是目录,不是单个.shp文件)
hdfs_shape_dir = "/<path>/shapefile_dir/"
# 本地临时目录
local_temp_dir = tempfile.mkdtemp()

# 下载目录下所有Shapefile相关文件
for file_name in hdfs_client.list(hdfs_shape_dir):
    if file_name.endswith(('.shp', '.shx', '.dbf', '.prj')):
        hdfs_client.download(f"{hdfs_shape_dir}{file_name}", os.path.join(local_temp_dir, file_name))

# 读取Shapefile
gdf = gpd.read_file(os.path.join(local_temp_dir, "<your-shapefile-name>.shp"))

# 查看数据
print(gdf.head())

# 清理临时目录(可选)
import shutil
shutil.rmtree(local_temp_dir)

方法二:使用PySpark结合GeoSpark扩展读取

GeoSpark是Spark的地理空间扩展库,支持直接读取HDFS上的Shapefile。

步骤:

  1. 下载GeoSpark的相关JAR包(如geospark-sql_2.12-1.4.0.jar、geospark-core_2.12-1.4.0.jar等),启动SparkSession时加载这些JAR。

  2. 实现代码:

from pyspark.sql import SparkSession

# 初始化SparkSession,加载GeoSpark JAR
spark = SparkSession.builder \
    .appName("read_shapefile") \
    .config("spark.jars", "/path/to/geospark-core.jar,/path/to/geospark-sql.jar") \
    .getOrCreate()

# 注册GeoSpark SQL函数
spark.sql("CREATE TEMPORARY VIEW shapefile_view USING org.datasyslab.geospark.sql.format.shapefile OPTIONS (path 'hdfs://<namenode-ip>:<port>/<path>/shapefile_dir/')")

# 读取为DataFrame
df = spark.sql("SELECT * FROM shapefile_view")

# 查看数据
df.show()

注意:使用GeoSpark时,HDFS路径需要指向Shapefile所在的目录(包含所有关联文件),而非单个.shp文件。

内容的提问来源于stack exchange,提问作者김희현

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:12:52