Pandas DataFrame: convert WKT into GeoJSON in a ne

2019-09-13 20:31发布

问题:

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...