I am trying to automate this portion of code in python (code shown for 2 polygons, I am trying to do the same for 10 000 polygons). Any ideas on how to implement this using for loop or whichever fastest way you recommend.

### Polygon 1 
def checkPolygon1(row):
    point = Point((row['X']), (row['Y']))
    return polygon1.contains(point)

#Apply fn to each row of dataframe (datacopy)
datacopy.apply(checkPolygon1, axis=1)

#Create new variable InPolygon1 in data if X, Y in shapely file 
datacopy['InPolygon1'] = datacopy.apply(checkPolygon1, axis=1)

### Polygon 2
def checkPolygon2(row):
    point = Point((row['X']), (row['Y']))
    return polygon2.contains(point)

datacopy.apply(checkPolygon2, axis=1)
#Create new variable InPolygon2 in data if X, Y in shapely file 
datacopy['InPolygon2'] = datacopy.apply(checkPolygon2, axis=1)
  • 3
    \$\begingroup\$ Your description is missing the purpose of the code. You say the code does something "for two polygons", but you didn't say what this "something" is. \$\endgroup\$ – Roland Illig Nov 20 '19 at 1:47

Both functions checkPolygon1 and checkPolygon2 perform essentially the same actions and only differ in specific polygon instance.
That's an appropriate case for Parameterize Function refactoring technique where polygon instance can serve as a factor.

Define a unified function point_in_polygon (don't forget about Python naming conventions):

def point_in_polygon(row, polygon):
    return polygon.contains(Point(row['X'], row['Y']))

Then, assuming that you already have a list or generator of polygons polygons:

for i, polygon in enumerate(polygons, 1):
    datacopy[f'InPolygon{i}'] = datacopy.apply(point_in_polygon, axis=1, polygon=polygon)
| improve this answer | |

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