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)