Skip to content
Advertisement

When do I need to use a GeoSeries when creating a GeoDataFrame, and when is a list enough?

JavaScript

I define a polygon:

JavaScript

and create a list of random points:

JavaScript

I want to know which points are within the polygon. I create a GeoDataFrame with a column called points, by first converting the points list to GeoSeries:

JavaScript

Then simply do:

JavaScript

which returns a pandas.core.series.Series of booleans, indicating which points are within the polygon.

However, if I don’t create the GeoDataFrame from a list, not a GeoSeries object:

JavaScript

and then do:

JavaScript

I get:

JavaScript

In the examples given on the geopandas.GeoDataFrame page, a GeoDataFrame is create from a list, not a GeoSeries of shapely.geometry.Point objects:

JavaScript

When do I need to convert my lists to GeoSeries first, and when can I keep them as lists when creating GeoDataFrames?

Advertisement

Answer

On the docs for geopandas.GeoDataFrame, where you got your example, there’s a little note:

Notice that the inferred dtype of ‘geometry’ columns is geometry.

Which can be seen here, and you can observe it yourself:

JavaScript

From the docs for geopandas.GeoSeries:

A Series object designed to store shapely geometry objects.

…so it makes sense that it would try to convert the objects it’s created with to the geometry dtype. In fact, when you try to create a GeoSeries with non-shapely objects, you’ll get a warning:

JavaScript

…which, as the warning says, will become an error in the future.


Since you’re not creating a GeoSeries object (your using a list instead), and since the column is not called geometry, the GeoDataFrame makes its dtype be the most general it can convert the objects within to – object. Therefore, since the column is of dtype object and not geometry, you can’t call geometry-specific methods, such as within.

If you need to use a list, you’ve two simple choices.

Method 1. Pass the geometry= keyword argument to GeoDataFrame():

JavaScript

Method 2. Use astype like you’d do with a normal dataframe:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement