5

I am new to Python and am trying check if a set of points are inside a polygon using Shapely as I am not able to install GeoPandas (tried for over a week now and am tired of fighting with Anaconda).

I have a folder of LAS files with coordinates in the filename and what I want to do is:

  1. read the filename
  2. parse it to x and y coordinates
  3. check if this xy coordinate is inside of a polygon

I am able to do the first 2 steps but am failing on step 3. My problem is that I have a set of polygon coordinates (xy) in a CSV file that are being read into a list:

Sample of the data :

156922.3097 6559238.263
157424.9655 6559462.937
157837.7369 6559395.169
158078.2783 6559284.668
158449.978 6558972.523

The code I am using to read the CSV file:

with open("xy_polygon.csv", 'r') as f_input:
    csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)
    xv = []
    yv = []
    for cols in csv_input:
        xv.append(float(cols[0]))
        yv.append(float(cols[1]))

and I am able to add the points by typing out something like this:

# x is a list of x-coordinates, y is list of y-coordinates
p1 = Polygon([[xv[0], yv[0]], [xv[1], yv[1]], [xv[2], yv[2]]])

But I would like to use both lists in the Polygon function, for example:

p1 = Polygon([[xv, yv]])

But I get the error:

ValueError: A LinearRing must have at least 3 coordinate tuples

I also tried:

p1 = Polygon([[xv[0], yv[0]], [xv[1], yv[1]], [xv[2], yv[2]]])
p1.append(Polygon([[xv[3], yv[3]], [xv[4], yv[4]], [xv[5], yv[5]]]))

which returned the following, so I am clearly doing this incorrectly.

'Polygon' object has no attribute 'append'

Can someone provide some tips as to how I could achieve this?

3
  • What does [xv, yv] mean? Could you please add the loop version? So that we may perhaps solve your problem easily? Commented Mar 2, 2021 at 10:02
  • Thanks Kadir, I edited the question to hopefully make it more clear.
    – nola
    Commented Mar 2, 2021 at 11:44
  • Please, do not forget about "What should I do when someone answers my question?"
    – Taras
    Commented Apr 11, 2022 at 6:33

1 Answer 1

6

The shapely Polygon class constructor can receive a sequence of coordinate tuples, which you can create using the zip function.

p = Polygon(list(zip(xv, yv)))

or even simpler, you may as well create a list of tuples in the first place

with open("xy_polygon.csv", 'r') as f_input:
    csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)
    coords = []
    for cols in csv_input:
        coords.append((float(cols[0]), float(cols[1])))
        
p = Polygon(coords)
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.