Laura Holewa
Laura Holewa

Reputation: 121

How do I create a numpy array that corresponds to whether a point is inside a numpy array of polygons?

Here is my attempt, but I get the error "AttributeError: 'numpy.ndarray' object has no attribute 'contains'" .

If any of you can help me to understand how to define 'y' in this code such that it is a numpy array with 1s corresponding to the index of polygons that contain the specified point and 0s corresponding to the index of polygons that do not contain the specified point I would appreciate it.

polygonss=[]
for i in range(0, len(verts)):
    polygonc = Polygon(verts[i])
    print (polygonc)
    polygonss.append(polygonc)
print (polygonss)
p=np.array(polygonss)
print (p)
vertsf=meshinformation_fine.celltoverticesandcentroid(0)[0]
point = Point(vertsf[0])
y=np.where(p.contains(point), 0, 1)
print (y)

Upvotes: 1

Views: 300

Answers (2)

mdurant
mdurant

Reputation: 28683

A numpy object array is not particularly useful to you here, you may as well do the process with a list comprehension

y = [p.contains(point) for p in polygonss]

However, if you are doing this for a large number of points, then I encourage you to read up on geopandas which enables you to do vectorised computations on geometries and apply them to tabular data.

Upvotes: 1

mrk
mrk

Reputation: 10386

First the error message is actually what keeps you from succeeding. .ndarray object just do not have that attribute contains

Which renders your question to one of those solutions, discussing on how to check whether an element is within a numpy Array.

One Thing that could work instead of contains is something following that line, if I understood correctly:

y = np.zeros(len(p))
for counter in range (0, len(p)):
    if point in p[counter]:
        y[counter] = 1 

Note: It would help if you would add exemplary values for your variables and the then expected output.

Upvotes: 0

Related Questions