Skip to content
Advertisement

Geopandas not exploding

JavaScript

Why isn’t geopandas exploding this series??? Below I have posted the first 5 rows. Clearly multilinestring and that function isn’t throwing any errors. Any suggestions?

Any other idea’s of how to convert multilinestring to linestring would be appreciated.

JavaScript

Advertisement

Answer

Quick tip for your next question ;) – since you’ve provided full WKT objects, we actually can create a MRE directly from your question:

JavaScript

In comments, you’ve figured out you can convert from WKT to a GeometryArray using geopandas.GeoSeries.from_wkt:

JavaScript

However, if you assign the result to the existing geodataframe, you need to tell geopandas that the new values are the geometry column. You think of geopandas as pandas + special handling of one single column. Pandas is fully capable of working with GeometryArray type data. Geopandas only really kicks into gear when it knows that one column is the special geometry column to which it can apply geospatial operations. So to tell it that “multilinestring” is this special column (or even “geometry” if you’ve assigned it after creating the GeoDataFrame), you need to call gdf.set_geometry:

JavaScript

Now that we’ve done this, geopandas knows that “multilinestring” is the special geometry column. This would have raised an error prior to the last step:

JavaScript

Now that we’ve done this, all of geopandas’ spatial ops, including explode, will work as expected:

JavaScript

See the Geopandas User Guide for a larger discussion of the structure of the GeoDataFrame and the importance of the designated geometry column. Here’s an exerpt:

A GeoDataFrame is a tabular data structure that contains a GeoSeries.

The most important property of a GeoDataFrame is that it always has one GeoSeries column that holds a special status. This GeoSeries is referred to as the GeoDataFrame’s “geometry”. When a spatial method is applied to a GeoDataFrame (or a spatial attribute like area is called), this commands will always act on the “geometry” column.

The “geometry” column – no matter its name – can be accessed through the geometry attribute (gdf.geometry), and the name of the geometry column can be found by typing gdf.geometry.name.

A GeoDataFrame may also contain other columns with geometrical (shapely) objects, but only one column can be the active geometry at a time. To change which column is the active geometry column, use the GeoDataFrame.set_geometry() method.

Advertisement