【问题标题】:Converting a CSV with a WKT column to a Shapefile将带有 WKT 列的 CSV 转换为 Shapefile
【发布时间】:2015-08-10 19:37:51
【问题描述】:

Python 中使用ogr2ogr,我正在尝试将CSV 转换为shapefileCSV 中名为“Polygon”的一列包含 WKT,如下所示:POLYGON((long lat, long lat, long lat, etc.)) 目前,我可以使用正确的投影制作多边形 shapefile,但几何图形为空。

如何修改我的ogr2ogr 参数以使用每行中的WKT 正确创建几何图形?目前我有这样的事情:

ogr2ogr.main(["", "-a_srs", "EPSG:4326", "-f", "ESRI Shapefile", "output.shp", "input.csv", "-nlt", "POLYGON"])

【问题讨论】:

  • 欢迎来到 SO 和不错的第一篇文章。希望有人能够在 SO 上为您提供帮助。如果您在一两天后没有收到任何回复,您也可以查看GIS SE 网站。你的帖子是关于编码的,所以它也适合这里。
  • 不要cross-post

标签: python csv gdal shapefile wkt


【解决方案1】:

我不太习惯 ogr2ogr.py,但如果你了解一些有关 ogr 的 python 绑定的基础知识,它可以很容易地完成。这是一个简单的例子,可以做你想做的事情。

import ogr, osr, csv

spatialref = osr.SpatialReference()  # Set the spatial ref.
spatialref.SetWellKnownGeogCS('WGS84')  # WGS84 aka ESPG:4326
driver = ogr.GetDriverByName("ESRI Shapefile") # Shapefile driver
dstfile = driver.CreateDataSource('output.shp') # Your output file

# Please note that it will fail if a file with the same name already exists
dstlayer = dstfile.CreateLayer("layer", spatialref, geom_type=ogr.wkbPolygon) 

# Add the other attribute fields needed with the following schema :
fielddef = ogr.FieldDefn("ID", ogr.OFTInteger)
fielddef.SetWidth(10)
dstlayer.CreateField(fielddef)

fielddef = ogr.FieldDefn("Name", ogr.OFTString)
fielddef.SetWidth(80)
dstlayer.CreateField(fielddef)

# Read the features in your csv file:
with open('/path/to/file.csv') as file_input:
    reader = csv.reader(file_input)  # Can be more intuitive with a DictReader (adapt to your needs)
    next(reader) # Skip the header
    for nb, row in enumerate(reader): 
        # WKT is in the second field in my test file :
        poly = ogr.CreateGeometryFromWkt(row[1])
        feature = ogr.Feature(dstlayer.GetLayerDefn())
        feature.SetGeometry(poly)
        feature.SetField("ID", nb) # A field with an unique id.
        feature.SetField("Name", row[0]) # The name (expected to be in the first column here)
        dstlayer.CreateFeature(feature)
    feature.Destroy()
    dstfile.Destroy()

此代码假定您的 CSV 有两列,第一列包含要使用的名称,第二列包含 WKT 中所要求的几何图形,例如以下形式的内容:

"Name","Polygons"
"Name1","POLYGON((1 1,5 1,5 5,1 5,1 1))"
"Name2","POLYGON((6 3,9 2,9 4,6 3))"

当然,它需要根据您的具体情况进行调整,但是这个 sn-p 代码可以是第一次开始,并且可以完成这项工作。
(如果你想要一些关于 GDAL/ogr python 绑定的其他例子,你可以看看these recipes

【讨论】:

  • 感谢 mgc 的两个回答。作为一个对 Python 和一般编程不熟悉的人,真的很感激。我会先尝试用this 修改我的代码,如果失败,我会回到这个答案。
  • 你能解释一下“with open('input.shp') as file_input”部分吗?我正在尝试使用 scrupt,但出现错误: FileNotFoundError: [Errno 2] No such file or directory: 'input.shp' 我认为这是新名称
  • @Reut 这绝对是我的代码中的一个错误。您必须将“input.shp”替换为 csv 文件的路径。我将编辑我的答案。
  • @Reut 我编辑了我的帖子,如果还不清楚,请不要犹豫。
猜你喜欢
  • 2020-08-25
  • 1970-01-01
  • 2022-09-25
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
相关资源
最近更新 更多