I've tried many, many many, ways to find out if a point is in a GIS polygon based on many great posts, but I can't get any to work properly. Specifically I created a grid of points covering the bounding box of Japan, and now I want to keep only the ones that are actually over Japan.
Here is one way I tried to get a GIS shapefile for Japan:
world = gp.read_file(gp.datasets.get_path('naturalearth_lowres')) JapanShapes = world[world.name == "Japan"] geoJapanShapes = gp.GeoDataFrame(JapanShapes2) geoJapanShape = geoJapanShapes['geometry'].unary_union
I have millions of point data in a geodataframe, but here's just one point (Tokyo station).
allCoords = pd.DataFrame([[35.6812,139.7671]], columns=["lat","lon"]) allCoords['geometry'] = allCoords.apply(lambda row: "POINT ("+str(row.lat)+" "+str(row.lon)+")", axis=1) allCoords = gp.GeoDataFrame(allCoords) allCoords['geometry'] = allCoords['geometry'].apply(wkt.loads)
Now, if test whether Tokyo station is in Japan:
print(allCoords['geometry'].within(geoJapanShape)) >>>> False
However, the last time I checked Tokyo station was within Japan. And if I do:
coordsWithinJapan = allCoords[allCoords.apply(lambda row: row['geometry'].within(geoJapanShapes), axis=1)] >>>> AttributeError: ("'GeoDataFrame' object has no attribute '_geom'", 'occurred at index 0')
Based on several other posts I also tried:
from geopandas.tools import sjoin gridWithinJapan = sjoin(geoHexData, geoJapanShapes, how='left', op='within')
Which just returns every point in the original data. If I try with the
inner option I instead get an empty dataframe.
So both methods (kinda) run on my data, but neither method is working to accurately report whether a point is within the boundary. Other versions gave me
crs errors, but I don't how to deal with that considering my points are hand-made. Another had a problem because maybe/apparently that shapefile is a multipolygon, which it couldn't handle. No matter what I try, I seem to be doing something wrong, but I can't find the error.
How do I actually determine whether my points are in my shape?