从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, replaceitem.genwith the correct column name (likeitem.city_nameor 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
相关产品推荐
相关产品推荐

