Geographic Information Systems Asked by Felipe D. on January 2, 2021
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 betterquicker 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
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)
Yes, there is to_wkt
function 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
Correct answer by martinfleis on January 2, 2021
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
Answered by gene on January 2, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP