Pandas DataFrame: convert WKT into GeoJSON in a new column using Lambda function

旧巷老猫 提交于 2020-01-06 06:51:38

问题


I have some data in this format:

Dep       Dest        geom
----      ----        -----
EDDF      KIAD        LINESTRING(3.961389 43.583333, 3.968056 43.580....

Which contains flight trajectories. The geom column contains the coordinates in WKT format. It is possible to convert them via the library geomet to GeoJSON format, which I want to do in a new column.

In order to do this efficiently with Pandas, I am trying to do:

from geomet import wkt
import json

df = .... #load data to df
df['geojson'] =  df['geom'].apply(lambda x: json.dumps(wkt.loads(x['geom'] )))

Which does not work. Any way to make it happen?


回答1:


Try changing the following line:

df['geojson'] =  df['geom'].apply(lambda x: json.dumps(wkt.loads(x['geom'] )))

into this one:

df['geojson'] =  df['geom'].apply(lambda x: json.dumps(wkt.loads(x)))

This produce the desired results:

from geomet import wkt
import json

#Generate dataframe
df = pd.DataFrame({"Dep":["EDDf"],
                   "Dest": ["KIAD"],
                   "geom": ["LINESTRING(3.961389 43.583333, 3.968056 43.580)"]})


#Apply function to create new column
df["geojson"] = df["geom"].apply(lambda x: json.dumps(wkt.loads(x)))

This creates:

    Dep  Dest                                             geom                                            geojson
0  EDDf  KIAD  LINESTRING(3.961389 43.583333, 3.968056 43.580)  {"type": "LineString", "coordinates": [[3.9613...


来源:https://stackoverflow.com/questions/44566744/pandas-dataframe-convert-wkt-into-geojson-in-a-new-column-using-lambda-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!