Skip to content

Commit

Permalink
Added methods from_csv and from_dataframe to geodataframe.
Browse files Browse the repository at this point in the history
from_dataframe takes a pandas dataframe, requires columns that
correspond to x/y, converts to point objects, and then creates a
geodataframe. from_csv simply wraps from_dataframe.
  • Loading branch information
jdmcbr committed Aug 12, 2015
1 parent b3d93bd commit ddefbd4
Showing 1 changed file with 61 additions and 1 deletion.
62 changes: 61 additions & 1 deletion geopandas/geodataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import numpy as np
from pandas import DataFrame, Series
from shapely.geometry import mapping, shape
from shapely.geometry import mapping, shape, Point
from shapely.geometry.base import BaseGeometry
from six import string_types

Expand Down Expand Up @@ -197,6 +197,66 @@ def from_features(cls, features, crs=None):
df.crs = crs
return df

@classmethod
def from_dataframe(cls, df, xcol, ycol, crs=None):
"""
Alternate constructor to create a GeoDataFrame from a pandas
DataFrame in which two columns specify x/y coordinates.
Parameters
----------
df : pandas DataFrame
xcol : str
Label specifying column name of x coordinate.
ycol : str
Label specifying column name of y coordinate.
Returns
-------
geodataframe : GeoDataFrame
"""

if xcol not in df.keys():
raise KeyError("%s not found in dataframe" % xcol)
if ycol not in df.keys():
raise KeyError("%s not found in dataframe" % ycol)

attr_keys = set(df.keys()).difference(set([xcol, ycol]))
points = [dict(geometry=Point(row[xcol], row[ycol]),
**row[attr_keys].to_dict()) for (i, row)
in df.iterrows()]
geodf = GeoDataFrame.from_dict(points)

return geodf

@classmethod
def from_csv(cls, filename, xcol, ycol, crs=None, **kwargs):
"""
Alternate constructor to create a GeoDataFrame from a csv file in
which two columns specify x/y coordinates. Wraps from_dataframe method.
Parameters
----------
df : pandas DataFrame
xcol : str
Label specifying column name of x coordinate.
ycol : str
Label specifying column name of y coordinate.
crs : str (optional)
Coordinate system
Remaining **kwargs are passed to pandas.DataFrame.from_csv
Returns
-------
geodataframe : GeoDataFrame
"""

df = DataFrame.from_csv(filename, **kwargs)
geodf = cls.from_dataframe(df, xcol, ycol, crs=crs)

return geodf

@classmethod
def from_postgis(cls, sql, con, geom_col='geom', crs=None, index_col=None,
coerce_float=True, params=None):
Expand Down

0 comments on commit ddefbd4

Please sign in to comment.