4

Is there a quick way to produce a column/series containing the WKTs of all the geometries in a GeoPandas GeoDataFrame?

I got around this using the apply function (see example below), but I just wanted to check if there is a better\quicker way to do this.

import geopandas as gpd
from shapely.geometry import Point

mydf = gpd.GeoDataFrame({'x':[1,2,3],
                         'y':['a','b','c'],
                         'geometry':[Point([0,0]),Point([1,1]),Point([2,2])]},
                        geometry='geometry')

def get_wkt(geom):
    return geom.wkt

wkt_col = mydf.geometry.apply(get_wkt)

print(type(wkt_col))
print(wkt_col) 

The output I'm looking for (which the code above produces) is copied below:

<class 'pandas.core.series.Series'>
0    POINT (0 0)
1    POINT (1 1)
2    POINT (2 2)
Name: geometry, dtype: object

Edit

Here are some performance measures from the main suggestions:

# My original method:
mydf.geometry.apply(get_wkt)
267 µs ± 9.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


# martinfleis' method:
gpd.array.to_wkt(mydf.geometry.values)
57.9 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)


# gene's first method:
mydf.apply(lambda row:row['geometry'].wkt, axis=1)
461 µs ± 4.46 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


# gene's second method
[geom.wkt for geom in mydf.geometry]
61.6 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
4

UPDATE: As of GeoPandas 0.9, there is a to_wkt method.

mydf['wkt'] = mydf.geometry.to_wkt()

Yes, there is to_wkt method in semi-private array module. I think it should be public in future, will have a look into that.

Use it as following to get an array of WKTs.

wkt_array = gpd.array.to_wkt(mydf.geometry.values)
mydf['wkt'] = wkt_array
1
1

Or

mydf["wkt"]= mydf.apply(lambda row:row['geometry'].wkt, axis=1)
mydf
   x  y            geometry          wkt
0  1  a  POINT (0.00000 0.00000)  POINT (0 0)
1  2  b  POINT (1.00000 1.00000)  POINT (1 1)
2  3  c  POINT (2.00000 2.00000)  POINT (2 2)

Or

wkt = [geom.wkt for geom in mydf.geometry]
mydf['wkt']=wkt
1
  • Thanks for the suggestion, @gene! The first method you suggest is ostensibly identical to the alternative I showed in my question. The list comprehension version, though, is really quick! Thanks! – Felipe D. Nov 6 '20 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.