Search code examples
pandasdataframecsvgeometrycontains

using csv instead of geodataframe: 'str' object has no attribute 'contains'


I have a geodataframe, named gdf2, of the municipalities of the Netherlands, in which the attribute table looks like this: enter image description here

Using the following code returns me whether a coordinate (point) lies within a certain municipality:

from shapely.geometry import Point

point = Point(6.56667, 53.21917)

for i in range(len(gdf2['geometry'])):
  if gdf2['geometry'][i].contains(point) == True:
     print(gdf2['statnaam'][i])

This code returns me correctly 'Groningen', the municipality the point is in.

Now I want to do the same thing, but with a csv file of this. A user inputs the latitude and longitude, named lat and lon here. Here, lat and lon are type floats.

from shapely.geometry import Point

gdf2.to_csv('gdf2.csv')

gdf_csv = pd.read_csv('gdf2.csv')

point = Point(lon, lat)

for i in range(len(gdf_csv['geometry'])):
    if gdf_csv['geometry'][i].contains(point) == True:
       print(gdf_csv['statnaam'][i])

When I run this, it gives me the error: 'str' object has no attribute 'contains'.

What is going wrong here? I should be able to do the same in a csv file, right?


Solution

  • I solved this by converting the csv basically back to GDF:

    from shapely import wkt
    gdf_csv.geometry = gdf_csv.geometry.apply(wkt.loads)
    

    Now the following code works!

    point = Point(lon, lat)
    
    for i in range(len(gdf_csv['geometry'])):
        if gdf_csv['geometry'][i].contains(point) == True:
           print(gdf_csv['statnaam'][i])