'Find Polygon Coordinates from Shapefile using Python Geopandas
ERROR:
TypeError: 'LineString' object is not iterable
I am trying to find the bottom right corner of the Polygon in this .shp
file. This .shp
file is a square but other files may be a rectangle/triangle.
I want to use Geopandas and apparently I can obtain this using the read_file()
method. I am quite new to SHPs and I have the .shx
, .dpf
files however when I enter just the .shp
in this method, I am not able to loop through the polygon coordinates.
Here is my code - I want to capture the bottom right corner in a variable, currently all_cords
will capture all of them, so I need to find a way to get over this error and then capture the bottom right corner,
import geopandas as gpd
import numpy as np
shapepath = r"FieldAlyticsCanada_WesternSales_AlexOlson_CouttsAgro2022_CouttsAgro_7-29-23.shp"
df = gpd.read_file(shapepath)
g = [i for i in df.geometry]
all_coords = []
for b in g[0].boundary: # error happens here
coords = np.dstack(b.coords.xy).tolist()
all_coords.append(*coords)
print(all_coords)
Solution 1:[1]
You can use much simpler concepts
bounds
provides tuple (minx, miny, maxx, maxy)shapely.ops.nearest_points()
can be used to find nearest point to maxx, miny point
import geopandas as gpd
import numpy as np
import shapely.geometry
import shapely.ops
import pandas as pd
shapepath = (
r"FieldAlyticsCanada_WesternSales_AlexOlson_CouttsAgro2022_CouttsAgro_7-29-23.shp"
)
shapepath = gpd.datasets.get_path("naturalearth_lowres")
df = gpd.read_file(shapepath)
# find point closest to bottom right corner of geometry (minx, maxy)
df["nearest"] = df["geometry"].apply(
lambda g: shapely.ops.nearest_points(
g,
shapely.geometry.Point(
g.bounds[2], g.bounds[1]
),
)[0]
)
# visualize outcome...
gdfn = gpd.GeoDataFrame(df["name"], geometry=df["nearest"], crs=df.crs)
m = df.drop(columns=["nearest"]).explore()
gdfn.explore(m=m, color="red")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rob Raymond |