Reputation: 492
I have a DataFrame which has a column of coordinates list looks like the following:
I want to make this DataFrame a GeoPandas DataFrame with a geometry
column. One way for doing this is to create two lists representing latitude and longitude and store the first and second element from the coors
column to latitude and longitude, respectively. Then sue gpd.points_from_xy
to build the geometry column. But this approach adds extra steps for building GeoPandas DataFrame. My question is how to build geometry
directly from the coors
list.
I add some test data here:
import pandas ad pd
import geopandas as gpd
data = {'id':[0,1,2,3], 'coors':[[41,-80],[40,-76],[35,-70],[35,-87]]}
df = pd.DataFrame.from_dict(data)
Upvotes: 2
Views: 4686
Reputation: 41
In the case that you have latitude and longitude in separated columns, You can do this:
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
def create_geometry(row):
row["geometry"] = Point(row["latitude"],row["longitude"])
return row
df = pd.read_[parquet|csv|etc]("file")
df = df.apply(create_geometry,axis=1)
gdf = gpd.GeoDataFrame(df,crs=4326)
Then, You can verify it doing:
df.geometry.head(1)
output
16 POINT (7.88507 -76.63130)
Name: geometry, dtype: geometry
Upvotes: 0
Reputation: 7824
You can just apply Point
to the 'coors'
column to generate point geometry.
from shapely.geometry import Point
df['geometry'] = df.coors.apply(Point)
gdf = gpd.GeoDataFrame(df) # you should also specify CRS
Upvotes: 4