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

从SHP文件多边形生成图时遭遇AttributeError:'str'对象无itertuples属性的解决方法求助

Fixing the 'str' object has no attribute 'itertuples' Error in Your Geospatial Code

Hey there! Let's break down what's causing this error and fix it step by step.

The Root Cause

Your mistake is a tiny syntax error in how you're loading the shapefile:

cities = gpd.read_file =('/Users/xxx/Desktop/Example/cities.shp')

Instead of calling the gpd.read_file() function and assigning its output (a GeoDataFrame) to cities, you're actually assigning the string file path directly to cities. That's why Python treats cities as a plain string—which doesn't have the itertuples() method you're trying to use.

Corrected Code

Here's the fixed version of your script, with a few quality-of-life tweaks:

import geopandas as gpd
import osmnx as ox

# Define your shapefile path (you can reuse this variable for reading)
path_to_shp = r'/Users/xxx/Desktop/Example/cities.shp'

# Correctly load the shapefile into a GeoDataFrame
cities = gpd.read_file(path_to_shp)

# Iterate over each row in the GeoDataFrame
for item in cities.itertuples():
    # Confirm the 'gen' field exists (adjust if your column has a different name!)
    print(item.gen)
    # Generate the graph from the polygon geometry
    graph = ox.graph_from_polygon(item.geometry)
    # Use an f-string for cleaner filename construction
    ox.save_graphml(graph, filepath=f'/Users/xxx/Desktop/{item.gen}.graphml')

Quick Checks to Avoid Future Headaches

  • Validate Column Names: Double-check that your shapefile actually has a column named gen. If not, replace item.gen with the correct column name (like item.city_name or whatever matches your data).
  • Confirm GeoDataFrame Load: After loading, run print(cities.head()) to make sure the shapefile loaded properly and you can see all your columns.
  • Path Best Practices: Using f-strings for file paths makes the code easier to read and less likely to have concatenation errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:07:38