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

ArcMap 10.5.1:用Python导出选中年份属性至新Shapefile

解决方法:批量导出指定年份的Shapefile

单个年份导出的基础实现

你已经成功用SelectLayerByAttribute_management筛选出了特定年份的数据,接下来只需要用ArcPy的CopyFeatures_management工具把选中的要素导出成新的Shapefile就行。针对1989年的示例代码如下:

import arcpy

# 设置工作空间(可选,方便统一管理文件路径)
arcpy.env.workspace = r"C:\Your\Target\Workspace\Path"

# 选中1989年的数据
arcpy.SelectLayerByAttribute_management("Customers", "NEW_SELECTION", "Year=1989")

# 导出为指定格式的Shapefile
output_shp = "Customers_1989.shp"
arcpy.CopyFeatures_management("Customers", output_shp)

批量处理25个年份的优化方案

手动改年份跑25次代码太麻烦,推荐自动获取所有唯一年份并批量导出,效率更高:

import arcpy
from collections import OrderedDict

# 配置基础参数
arcpy.env.workspace = r"C:\Your\Target\Workspace\Path"
input_layer = "Customers"
year_field = "Year"

# 获取所有唯一的年份值(自动去重)
unique_years = []
with arcpy.da.SearchCursor(input_layer, [year_field]) as cursor:
    # 用OrderedDict保证年份顺序(可选,根据需求调整)
    unique_years = list(OrderedDict.fromkeys([row[0] for row in cursor]))

# 循环处理每个年份
for year in unique_years:
    # 构建属性筛选条件
    where_clause = f"{year_field} = {year}"
    # 选中当前年份的数据
    arcpy.SelectLayerByAttribute_management(input_layer, "NEW_SELECTION", where_clause)
    # 生成符合要求的输出文件名
    output_shp = f"Customers_{year}.shp"
    # 执行导出
    arcpy.CopyFeatures_management(input_layer, output_shp)
    print(f"已完成导出:{output_shp}")

关键注意事项

  • 如果Year字段是字符串类型,筛选条件要加单引号:f"{year_field} = '{year}'"
  • 若Customers不是已加载的图层,直接传入要素类的完整路径即可(比如r"C:\Data\Customers.shp")
  • 设置arcpy.env.workspace后,所有输出文件会自动保存到该路径下,无需重复写完整路径

内容的提问来源于stack exchange,提问作者PythonPerson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:19:28