-
Notifications
You must be signed in to change notification settings - Fork 901
/
geodataframe.py
2472 lines (2100 loc) · 94 KB
/
geodataframe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import warnings
import numpy as np
import pandas as pd
import shapely.errors
from pandas import DataFrame, Series
from pandas.core.accessor import CachedAccessor
from shapely.geometry import mapping, shape
from shapely.geometry.base import BaseGeometry
from geopandas.array import GeometryArray, GeometryDtype, from_shapely, to_wkb, to_wkt
from geopandas.base import GeoPandasBase, is_geometry_type
from geopandas.geoseries import GeoSeries
import geopandas.io
from geopandas.explore import _explore
from ._decorator import doc
from ._compat import HAS_PYPROJ
def _geodataframe_constructor_with_fallback(*args, **kwargs):
"""
A flexible constructor for GeoDataFrame._constructor, which falls back
to returning a DataFrame (if a certain operation does not preserve the
geometry column)
"""
df = GeoDataFrame(*args, **kwargs)
geometry_cols_mask = df.dtypes == "geometry"
if len(geometry_cols_mask) == 0 or geometry_cols_mask.sum() == 0:
df = pd.DataFrame(df)
return df
def _ensure_geometry(data, crs=None):
"""
Ensure the data is of geometry dtype or converted to it.
If input is a (Geo)Series, output is a GeoSeries, otherwise output
is GeometryArray.
If the input is a GeometryDtype with a set CRS, `crs` is ignored.
"""
if is_geometry_type(data):
if isinstance(data, Series):
data = GeoSeries(data)
if data.crs is None and crs is not None:
# Avoids caching issues/crs sharing issues
data = data.copy()
data.crs = crs
return data
else:
if isinstance(data, Series):
out = from_shapely(np.asarray(data), crs=crs)
return GeoSeries(out, index=data.index, name=data.name)
else:
out = from_shapely(data, crs=crs)
return out
crs_mismatch_error = (
"CRS mismatch between CRS of the passed geometries "
"and 'crs'. Use 'GeoDataFrame.set_crs(crs, "
"allow_override=True)' to overwrite CRS or "
"'GeoDataFrame.to_crs(crs)' to reproject geometries. "
)
class GeoDataFrame(GeoPandasBase, DataFrame):
"""
A GeoDataFrame object is a pandas.DataFrame that has a column
with geometry. In addition to the standard DataFrame constructor arguments,
GeoDataFrame also accepts the following keyword arguments:
Parameters
----------
crs : value (optional)
Coordinate Reference System of the geometry objects. Can be anything accepted by
:meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
such as an authority string (eg "EPSG:4326") or a WKT string.
geometry : str or array (optional)
If str, column to use as geometry. If array, will be set as 'geometry'
column on GeoDataFrame.
Examples
--------
Constructing GeoDataFrame from a dictionary.
>>> from shapely.geometry import Point
>>> d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
>>> gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")
>>> gdf
col1 geometry
0 name1 POINT (1 2)
1 name2 POINT (2 1)
Notice that the inferred dtype of 'geometry' columns is geometry.
>>> gdf.dtypes
col1 object
geometry geometry
dtype: object
Constructing GeoDataFrame from a pandas DataFrame with a column of WKT geometries:
>>> import pandas as pd
>>> d = {'col1': ['name1', 'name2'], 'wkt': ['POINT (1 2)', 'POINT (2 1)']}
>>> df = pd.DataFrame(d)
>>> gs = geopandas.GeoSeries.from_wkt(df['wkt'])
>>> gdf = geopandas.GeoDataFrame(df, geometry=gs, crs="EPSG:4326")
>>> gdf
col1 wkt geometry
0 name1 POINT (1 2) POINT (1 2)
1 name2 POINT (2 1) POINT (2 1)
See also
--------
GeoSeries : Series object designed to store shapely geometry objects
"""
_metadata = ["_geometry_column_name"]
_internal_names = DataFrame._internal_names + ["geometry"]
_internal_names_set = set(_internal_names)
_geometry_column_name = None
def __init__(self, data=None, *args, geometry=None, crs=None, **kwargs):
if (
kwargs.get("copy") is None
and isinstance(data, DataFrame)
and not isinstance(data, GeoDataFrame)
):
kwargs.update(copy=True)
super().__init__(data, *args, **kwargs)
# set_geometry ensures the geometry data have the proper dtype,
# but is not called if `geometry=None` ('geometry' column present
# in the data), so therefore need to ensure it here manually
# but within a try/except because currently non-geometries are
# allowed in that case
# TODO do we want to raise / return normal DataFrame in this case?
# if gdf passed in and geo_col is set, we use that for geometry
if geometry is None and isinstance(data, GeoDataFrame):
self._geometry_column_name = data._geometry_column_name
if crs is not None and data.crs != crs:
raise ValueError(crs_mismatch_error)
if (
geometry is None
and self.columns.nlevels == 1
and "geometry" in self.columns
):
# Check for multiple columns with name "geometry". If there are,
# self["geometry"] is a gdf and constructor gets recursively recalled
# by pandas internals trying to access this
if (self.columns == "geometry").sum() > 1:
raise ValueError(
"GeoDataFrame does not support multiple columns "
"using the geometry column name 'geometry'."
)
# only if we have actual geometry values -> call set_geometry
try:
if (
hasattr(self["geometry"].values, "crs")
and self["geometry"].values.crs
and crs
and not self["geometry"].values.crs == crs
):
raise ValueError(crs_mismatch_error)
self["geometry"] = _ensure_geometry(self["geometry"].values, crs)
except TypeError:
pass
else:
geometry = "geometry"
if geometry is not None:
if (
hasattr(geometry, "crs")
and geometry.crs
and crs
and not geometry.crs == crs
):
raise ValueError(crs_mismatch_error)
self.set_geometry(geometry, inplace=True, crs=crs)
if geometry is None and crs:
raise ValueError(
"Assigning CRS to a GeoDataFrame without a geometry column is not "
"supported. Supply geometry using the 'geometry=' keyword argument, "
"or by providing a DataFrame with column name 'geometry'",
)
def __setattr__(self, attr, val):
# have to special case geometry b/c pandas tries to use as column...
if attr == "geometry":
object.__setattr__(self, attr, val)
else:
super().__setattr__(attr, val)
def _get_geometry(self):
if self._geometry_column_name not in self:
if self._geometry_column_name is None:
msg = (
"You are calling a geospatial method on the GeoDataFrame, "
"but the active geometry column to use has not been set. "
)
else:
msg = (
"You are calling a geospatial method on the GeoDataFrame, "
f"but the active geometry column ('{self._geometry_column_name}') "
"is not present. "
)
geo_cols = list(self.columns[self.dtypes == "geometry"])
if len(geo_cols) > 0:
msg += (
f"\nThere are columns with geometry data type ({geo_cols}), and "
"you can either set one as the active geometry with "
'df.set_geometry("name") or access the column as a '
'GeoSeries (df["name"]) and call the method directly on it.'
)
else:
msg += (
"\nThere are no existing columns with geometry data type. You can "
"add a geometry column as the active geometry column with "
"df.set_geometry. "
)
raise AttributeError(msg)
return self[self._geometry_column_name]
def _set_geometry(self, col):
if not pd.api.types.is_list_like(col):
raise ValueError("Must use a list-like to set the geometry property")
self._persist_old_default_geometry_colname()
self.set_geometry(col, inplace=True)
geometry = property(
fget=_get_geometry, fset=_set_geometry, doc="Geometry data for GeoDataFrame"
)
def set_geometry(self, col, drop=None, inplace=False, crs=None):
"""
Set the GeoDataFrame geometry using either an existing column or
the specified input. By default yields a new object.
The original geometry column is replaced with the input.
Parameters
----------
col : column label or array-like
An existing column name or values to set as the new geometry column.
If values (array-like, (Geo)Series) are passed, then if they are named
(Series) the new geometry column will have the corresponding name,
otherwise the existing geometry column will be replaced. If there is
no existing geometry column, the new geometry column will use the
default name "geometry".
drop : boolean, default False
When specifying a named Series or an existing column name for `col`,
controls if the previous geometry column should be dropped from the
result. The default of False keeps both the old and new geometry column.
.. deprecated:: 1.0.0
inplace : boolean, default False
Modify the GeoDataFrame in place (do not create a new object)
crs : pyproj.CRS, optional
Coordinate system to use. The value can be anything accepted
by :meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
such as an authority string (eg "EPSG:4326") or a WKT string.
If passed, overrides both DataFrame and col's crs.
Otherwise, tries to get crs from passed col values or DataFrame.
Examples
--------
>>> from shapely.geometry import Point
>>> d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
>>> gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")
>>> gdf
col1 geometry
0 name1 POINT (1 2)
1 name2 POINT (2 1)
Passing an array:
>>> df1 = gdf.set_geometry([Point(0,0), Point(1,1)])
>>> df1
col1 geometry
0 name1 POINT (0 0)
1 name2 POINT (1 1)
Using existing column:
>>> gdf["buffered"] = gdf.buffer(2)
>>> df2 = gdf.set_geometry("buffered")
>>> df2.geometry
0 POLYGON ((3 2, 2.99037 1.80397, 2.96157 1.6098...
1 POLYGON ((4 1, 3.99037 0.80397, 3.96157 0.6098...
Name: buffered, dtype: geometry
Returns
-------
GeoDataFrame
See also
--------
GeoDataFrame.rename_geometry : rename an active geometry column
"""
# Most of the code here is taken from DataFrame.set_index()
if inplace:
frame = self
else:
frame = self.copy()
geo_column_name = self._geometry_column_name
if geo_column_name is None:
geo_column_name = "geometry"
if isinstance(col, (Series, list, np.ndarray, GeometryArray)):
if drop:
msg = (
"The `drop` keyword argument is deprecated and has no effect when "
"`col` is an array-like value. You should stop passing `drop` to "
"`set_geometry` when this is the case."
)
warnings.warn(msg, category=FutureWarning, stacklevel=2)
if isinstance(col, Series) and col.name is not None:
geo_column_name = col.name
level = col
elif hasattr(col, "ndim") and col.ndim > 1:
raise ValueError("Must pass array with one dimension only.")
else: # should be a colname
try:
level = frame[col]
except KeyError:
raise ValueError("Unknown column %s" % col)
if isinstance(level, DataFrame):
raise ValueError(
"GeoDataFrame does not support setting the geometry column where "
"the column name is shared by multiple columns."
)
given_colname_drop_msg = (
"The `drop` keyword argument is deprecated and in future the only "
"supported behaviour will match drop=False. To silence this "
"warning and adopt the future behaviour, stop providing "
"`drop` as a keyword to `set_geometry`. To replicate the "
"`drop=True` behaviour you should update "
"your code to\n`geo_col_name = gdf.active_geometry_name;"
" gdf.set_geometry(new_geo_col).drop("
"columns=geo_col_name).rename_geometry(geo_col_name)`."
)
if drop is False: # specifically False, not falsy i.e. None
# User supplied False explicitly, but arg is deprecated
warnings.warn(
given_colname_drop_msg,
category=FutureWarning,
stacklevel=2,
)
if drop:
del frame[col]
warnings.warn(
given_colname_drop_msg,
category=FutureWarning,
stacklevel=2,
)
else:
# if not dropping, set the active geometry name to the given col name
geo_column_name = col
if not crs:
crs = getattr(level, "crs", None)
# Check that we are using a listlike of geometries
level = _ensure_geometry(level, crs=crs)
# ensure_geometry only sets crs on level if it has crs==None
level.crs = crs
# update _geometry_column_name prior to assignment
# to avoid default is None warning
frame._geometry_column_name = geo_column_name
frame[geo_column_name] = level
if not inplace:
return frame
def rename_geometry(self, col, inplace=False):
"""
Renames the GeoDataFrame geometry column to
the specified name. By default yields a new object.
The original geometry column is replaced with the input.
Parameters
----------
col : new geometry column label
inplace : boolean, default False
Modify the GeoDataFrame in place (do not create a new object)
Examples
--------
>>> from shapely.geometry import Point
>>> d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
>>> df = geopandas.GeoDataFrame(d, crs="EPSG:4326")
>>> df1 = df.rename_geometry('geom1')
>>> df1.geometry.name
'geom1'
>>> df.rename_geometry('geom1', inplace=True)
>>> df.geometry.name
'geom1'
Returns
-------
geodataframe : GeoDataFrame
See also
--------
GeoDataFrame.set_geometry : set the active geometry
"""
geometry_col = self.geometry.name
if col in self.columns:
raise ValueError(f"Column named {col} already exists")
else:
if not inplace:
return self.rename(columns={geometry_col: col}).set_geometry(
col, inplace
)
self.rename(columns={geometry_col: col}, inplace=inplace)
self.set_geometry(col, inplace=inplace)
@property
def active_geometry_name(self):
"""Return the name of the active geometry column
Returns a string name if a GeoDataFrame has an active geometry column set.
Otherwise returns None. You can also access the active geometry column using the
``.geometry`` property. You can set a GeoSeries to be an active geometry
using the :meth:`~GeoDataFrame.set_geometry` method.
Returns
-------
str
name of an active geometry column or None
See also
--------
GeoDataFrame.set_geometry : set the active geometry
"""
return self._geometry_column_name
@property
def crs(self):
"""
The Coordinate Reference System (CRS) represented as a ``pyproj.CRS``
object.
Returns None if the CRS is not set, and to set the value it
:getter: Returns a ``pyproj.CRS`` or None. When setting, the value
can be anything accepted by
:meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
such as an authority string (eg "EPSG:4326") or a WKT string.
Examples
--------
>>> gdf.crs # doctest: +SKIP
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
See also
--------
GeoDataFrame.set_crs : assign CRS
GeoDataFrame.to_crs : re-project to another CRS
"""
try:
return self.geometry.crs
except AttributeError:
raise AttributeError(
"The CRS attribute of a GeoDataFrame without an active "
"geometry column is not defined. Use GeoDataFrame.set_geometry "
"to set the active geometry column."
)
@crs.setter
def crs(self, value):
"""Sets the value of the crs"""
if self._geometry_column_name is None:
raise ValueError(
"Assigning CRS to a GeoDataFrame without a geometry column is not "
"supported. Use GeoDataFrame.set_geometry to set the active "
"geometry column.",
)
if hasattr(self.geometry.values, "crs"):
self.geometry.values.crs = value
else:
# column called 'geometry' without geometry
raise ValueError(
"Assigning CRS to a GeoDataFrame without an active geometry "
"column is not supported. Use GeoDataFrame.set_geometry to set "
"the active geometry column.",
)
def __setstate__(self, state):
# overriding DataFrame method for compat with older pickles (CRS handling)
crs = None
if isinstance(state, dict):
if "crs" in state and "_crs" not in state:
crs = state.pop("crs", None)
else:
crs = state.pop("_crs", None)
if crs is not None and not HAS_PYPROJ:
raise ImportError(
"Unpickling a GeoDataFrame with CRS requires the 'pyproj' package, "
"but it is not installed or does not import correctly. "
)
elif crs is not None:
from pyproj import CRS
crs = CRS.from_user_input(crs)
super().__setstate__(state)
# for some versions that didn't yet have CRS at array level -> crs is set
# at GeoDataFrame level with '_crs' (and not 'crs'), so without propagating
# to the GeoSeries/GeometryArray
try:
if crs is not None:
if self.geometry.values.crs is None:
self.crs = crs
except Exception:
pass
@classmethod
def from_dict(cls, data, geometry=None, crs=None, **kwargs):
"""
Construct GeoDataFrame from dict of array-like or dicts by
overriding DataFrame.from_dict method with geometry and crs
Parameters
----------
data : dict
Of the form {field : array-like} or {field : dict}.
geometry : str or array (optional)
If str, column to use as geometry. If array, will be set as 'geometry'
column on GeoDataFrame.
crs : str or dict (optional)
Coordinate reference system to set on the resulting frame.
kwargs : key-word arguments
These arguments are passed to DataFrame.from_dict
Returns
-------
GeoDataFrame
"""
dataframe = DataFrame.from_dict(data, **kwargs)
return cls(dataframe, geometry=geometry, crs=crs)
@classmethod
def from_file(cls, filename, **kwargs):
"""Alternate constructor to create a ``GeoDataFrame`` from a file.
It is recommended to use :func:`geopandas.read_file` instead.
Can load a ``GeoDataFrame`` from a file in any format recognized by
`pyogrio`. See http://pyogrio.readthedocs.io/ for details.
Parameters
----------
filename : str
File path or file handle to read from. Depending on which kwargs
are included, the content of filename may vary. See
:func:`pyogrio.read_dataframe` for usage details.
kwargs : key-word arguments
These arguments are passed to :func:`pyogrio.read_dataframe`, and can be
used to access multi-layer data, data stored within archives (zip files),
etc.
Examples
--------
>>> import geodatasets
>>> path = geodatasets.get_path('nybb')
>>> gdf = geopandas.GeoDataFrame.from_file(path)
>>> gdf # doctest: +SKIP
BoroCode BoroName Shape_Leng Shape_Area \
geometry
0 5 Staten Island 330470.010332 1.623820e+09 MULTIPOLYGON ((\
(970217.022 145643.332, 970227....
1 4 Queens 896344.047763 3.045213e+09 MULTIPOLYGON ((\
(1029606.077 156073.814, 102957...
2 3 Brooklyn 741080.523166 1.937479e+09 MULTIPOLYGON ((\
(1021176.479 151374.797, 102100...
3 1 Manhattan 359299.096471 6.364715e+08 MULTIPOLYGON ((\
(981219.056 188655.316, 980940....
4 2 Bronx 464392.991824 1.186925e+09 MULTIPOLYGON ((\
(1012821.806 229228.265, 101278...
The recommended method of reading files is :func:`geopandas.read_file`:
>>> gdf = geopandas.read_file(path)
See also
--------
read_file : read file to GeoDataFame
GeoDataFrame.to_file : write GeoDataFrame to file
"""
return geopandas.io.file._read_file(filename, **kwargs)
@classmethod
def from_features(cls, features, crs=None, columns=None):
"""
Alternate constructor to create GeoDataFrame from an iterable of
features or a feature collection.
Parameters
----------
features
- Iterable of features, where each element must be a feature
dictionary or implement the __geo_interface__.
- Feature collection, where the 'features' key contains an
iterable of features.
- Object holding a feature collection that implements the
``__geo_interface__``.
crs : str or dict (optional)
Coordinate reference system to set on the resulting frame.
columns : list of column names, optional
Optionally specify the column names to include in the output frame.
This does not overwrite the property names of the input, but can
ensure a consistent output format.
Returns
-------
GeoDataFrame
Notes
-----
For more information about the ``__geo_interface__``, see
https://gist.github.com/sgillies/2217756
Examples
--------
>>> feature_coll = {
... "type": "FeatureCollection",
... "features": [
... {
... "id": "0",
... "type": "Feature",
... "properties": {"col1": "name1"},
... "geometry": {"type": "Point", "coordinates": (1.0, 2.0)},
... "bbox": (1.0, 2.0, 1.0, 2.0),
... },
... {
... "id": "1",
... "type": "Feature",
... "properties": {"col1": "name2"},
... "geometry": {"type": "Point", "coordinates": (2.0, 1.0)},
... "bbox": (2.0, 1.0, 2.0, 1.0),
... },
... ],
... "bbox": (1.0, 1.0, 2.0, 2.0),
... }
>>> df = geopandas.GeoDataFrame.from_features(feature_coll)
>>> df
geometry col1
0 POINT (1 2) name1
1 POINT (2 1) name2
"""
# Handle feature collections
if hasattr(features, "__geo_interface__"):
fs = features.__geo_interface__
else:
fs = features
if isinstance(fs, dict) and fs.get("type") == "FeatureCollection":
features_lst = fs["features"]
else:
features_lst = features
rows = []
for feature in features_lst:
# load geometry
if hasattr(feature, "__geo_interface__"):
feature = feature.__geo_interface__
row = {
"geometry": shape(feature["geometry"]) if feature["geometry"] else None
}
# load properties
properties = feature["properties"]
if properties is None:
properties = {}
row.update(properties)
rows.append(row)
return cls(rows, columns=columns, crs=crs)
@classmethod
def from_postgis(
cls,
sql,
con,
geom_col="geom",
crs=None,
index_col=None,
coerce_float=True,
parse_dates=None,
params=None,
chunksize=None,
):
"""
Alternate constructor to create a ``GeoDataFrame`` from a sql query
containing a geometry column in WKB representation.
Parameters
----------
sql : string
con : sqlalchemy.engine.Connection or sqlalchemy.engine.Engine
geom_col : string, default 'geom'
column name to convert to shapely geometries
crs : optional
Coordinate reference system to use for the returned GeoDataFrame
index_col : string or list of strings, optional, default: None
Column(s) to set as index(MultiIndex)
coerce_float : boolean, default True
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
parse_dates : list or dict, default None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict
corresponds to the keyword arguments of
:func:`pandas.to_datetime`. Especially useful with databases
without native Datetime support, such as SQLite.
params : list, tuple or dict, optional, default None
List of parameters to pass to execute method.
chunksize : int, default None
If specified, return an iterator where chunksize is the number
of rows to include in each chunk.
Examples
--------
PostGIS
>>> from sqlalchemy import create_engine # doctest: +SKIP
>>> db_connection_url = "postgresql://myusername:mypassword@myhost:5432/mydb"
>>> con = create_engine(db_connection_url) # doctest: +SKIP
>>> sql = "SELECT geom, highway FROM roads"
>>> df = geopandas.GeoDataFrame.from_postgis(sql, con) # doctest: +SKIP
SpatiaLite
>>> sql = "SELECT ST_Binary(geom) AS geom, highway FROM roads"
>>> df = geopandas.GeoDataFrame.from_postgis(sql, con) # doctest: +SKIP
The recommended method of reading from PostGIS is
:func:`geopandas.read_postgis`:
>>> df = geopandas.read_postgis(sql, con) # doctest: +SKIP
See also
--------
geopandas.read_postgis : read PostGIS database to GeoDataFrame
"""
df = geopandas.io.sql._read_postgis(
sql,
con,
geom_col=geom_col,
crs=crs,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
params=params,
chunksize=chunksize,
)
return df
def to_json(
self, na="null", show_bbox=False, drop_id=False, to_wgs84=False, **kwargs
):
"""
Returns a GeoJSON representation of the ``GeoDataFrame`` as a string.
Parameters
----------
na : {'null', 'drop', 'keep'}, default 'null'
Indicates how to output missing (NaN) values in the GeoDataFrame.
See below.
show_bbox : bool, optional, default: False
Include bbox (bounds) in the geojson
drop_id : bool, default: False
Whether to retain the index of the GeoDataFrame as the id property
in the generated GeoJSON. Default is False, but may want True
if the index is just arbitrary row numbers.
to_wgs84: bool, optional, default: False
If the CRS is set on the active geometry column it is exported as
WGS84 (EPSG:4326) to meet the `2016 GeoJSON specification
<https://tools.ietf.org/html/rfc7946>`_.
Set to True to force re-projection and set to False to ignore CRS. False by
default.
Notes
-----
The remaining *kwargs* are passed to json.dumps().
Missing (NaN) values in the GeoDataFrame can be represented as follows:
- ``null``: output the missing entries as JSON null.
- ``drop``: remove the property from the feature. This applies to each
feature individually so that features may have different properties.
- ``keep``: output the missing entries as NaN.
If the GeoDataFrame has a defined CRS, its definition will be included
in the output unless it is equal to WGS84 (default GeoJSON CRS) or not
possible to represent in the URN OGC format, or unless ``to_wgs84=True``
is specified.
Examples
--------
>>> from shapely.geometry import Point
>>> d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
>>> gdf = geopandas.GeoDataFrame(d, crs="EPSG:3857")
>>> gdf
col1 geometry
0 name1 POINT (1 2)
1 name2 POINT (2 1)
>>> gdf.to_json()
'{"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", \
"properties": {"col1": "name1"}, "geometry": {"type": "Point", "coordinates": [1.0,\
2.0]}}, {"id": "1", "type": "Feature", "properties": {"col1": "name2"}, "geometry"\
: {"type": "Point", "coordinates": [2.0, 1.0]}}], "crs": {"type": "name", "properti\
es": {"name": "urn:ogc:def:crs:EPSG::3857"}}}'
Alternatively, you can write GeoJSON to file:
>>> gdf.to_file(path, driver="GeoJSON") # doctest: +SKIP
See also
--------
GeoDataFrame.to_file : write GeoDataFrame to file
"""
if to_wgs84:
if self.crs:
df = self.to_crs(epsg=4326)
else:
raise ValueError(
"CRS is not set. Cannot re-project to WGS84 (EPSG:4326)."
)
else:
df = self
geo = df.to_geo_dict(na=na, show_bbox=show_bbox, drop_id=drop_id)
# if the geometry is not in WGS84, include CRS in the JSON
if df.crs is not None and not df.crs.equals("epsg:4326"):
auth_crsdef = self.crs.to_authority()
allowed_authorities = ["EDCS", "EPSG", "OGC", "SI", "UCUM"]
if auth_crsdef is None or auth_crsdef[0] not in allowed_authorities:
warnings.warn(
"GeoDataFrame's CRS is not representable in URN OGC "
"format. Resulting JSON will contain no CRS information.",
stacklevel=2,
)
else:
authority, code = auth_crsdef
ogc_crs = f"urn:ogc:def:crs:{authority}::{code}"
geo["crs"] = {"type": "name", "properties": {"name": ogc_crs}}
return json.dumps(geo, **kwargs)
@property
def __geo_interface__(self):
"""Returns a ``GeoDataFrame`` as a python feature collection.
Implements the `geo_interface`. The returned python data structure
represents the ``GeoDataFrame`` as a GeoJSON-like
``FeatureCollection``.
This differs from :meth:`to_geo_dict` only in that it is a property with
default args instead of a method.
CRS of the dataframe is not passed on to the output, unlike
:meth:`~GeoDataFrame.to_json()`.
Examples
--------
>>> from shapely.geometry import Point
>>> d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
>>> gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")
>>> gdf
col1 geometry
0 name1 POINT (1 2)
1 name2 POINT (2 1)
>>> gdf.__geo_interface__
{'type': 'FeatureCollection', 'features': [{'id': '0', 'type': 'Feature', \
'properties': {'col1': 'name1'}, 'geometry': {'type': 'Point', 'coordinates': (1.0\
, 2.0)}, 'bbox': (1.0, 2.0, 1.0, 2.0)}, {'id': '1', 'type': 'Feature', 'properties\
': {'col1': 'name2'}, 'geometry': {'type': 'Point', 'coordinates': (2.0, 1.0)}, 'b\
box': (2.0, 1.0, 2.0, 1.0)}], 'bbox': (1.0, 1.0, 2.0, 2.0)}
"""
return self.to_geo_dict(na="null", show_bbox=True, drop_id=False)
def iterfeatures(self, na="null", show_bbox=False, drop_id=False):
"""
Returns an iterator that yields feature dictionaries that comply with
__geo_interface__
Parameters
----------
na : str, optional
Options are {'null', 'drop', 'keep'}, default 'null'.
Indicates how to output missing (NaN) values in the GeoDataFrame
- null: output the missing entries as JSON null
- drop: remove the property from the feature. This applies to each feature \
individually so that features may have different properties
- keep: output the missing entries as NaN
show_bbox : bool, optional
Include bbox (bounds) in the geojson. Default False.
drop_id : bool, default: False
Whether to retain the index of the GeoDataFrame as the id property
in the generated GeoJSON. Default is False, but may want True
if the index is just arbitrary row numbers.
Examples
--------
>>> from shapely.geometry import Point
>>> d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
>>> gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")
>>> gdf
col1 geometry
0 name1 POINT (1 2)
1 name2 POINT (2 1)
>>> feature = next(gdf.iterfeatures())
>>> feature
{'id': '0', 'type': 'Feature', 'properties': {'col1': 'name1'}, 'geometry': {\
'type': 'Point', 'coordinates': (1.0, 2.0)}}
"""
if na not in ["null", "drop", "keep"]:
raise ValueError("Unknown na method {0}".format(na))
if self._geometry_column_name not in self:
raise AttributeError(
"No geometry data set (expected in column '%s')."
% self._geometry_column_name
)
ids = np.array(self.index, copy=False)
geometries = np.array(self[self._geometry_column_name], copy=False)
if not self.columns.is_unique:
raise ValueError("GeoDataFrame cannot contain duplicated column names.")
properties_cols = self.columns.drop(self._geometry_column_name)
if len(properties_cols) > 0:
# convert to object to get python scalars.
properties_cols = self[properties_cols]
properties = properties_cols.astype(object)
na_mask = pd.isna(properties_cols).values
if na == "null":
properties[na_mask] = None
for i, row in enumerate(properties.values):
geom = geometries[i]
if na == "drop":
na_mask_row = na_mask[i]
properties_items = {
k: v
for k, v, na in zip(properties_cols, row, na_mask_row)