Python – How to Make Polygon from XY Coordinates List Using Shapely

csvpolygon-creationpythonshapelyxy

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?

Best Answer

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)