0

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)
1
  • You're way overcomplicating the beauty of geopandas. Try printing out some things like: df.boundary, df.x, df.y, df.bounds to get a feel for what it's doing. Loops are basically never the best option when it comes to pandas, at worst you can use .apply() for scenarios where a built in function doesn't cut it. Commented May 4, 2022 at 9:21

1 Answer 1

0

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.