internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: geopandas/geopandas

Issue:
ENH: preserve column order in read_file
Idea from http://gis.stackexchange.com/questions/216963/preserve-column-order-of-geopandas-file-read/217084#217084

For shapefiles, fiona saves the properties in the `meta` attribute as an OrderedDict, so we should be able to get the actual order of the columns in the file from that and rearrange the columns of the output accordingly.


Discussion:

Resolving patch:
diff --git a/geopandas/io/file.py b/geopandas/io/file.py
--- a/geopandas/io/file.py
+++ b/geopandas/io/file.py
@@ -14,7 +14,7 @@ def read_file(filename, **kwargs):
 
     *filename* is either the absolute or relative path to the file to be
     opened and *kwargs* are keyword args to be passed to the `open` method
-    in the fiona library when opening the file. For more information on 
+    in the fiona library when opening the file. For more information on
     possible keywords, type: ``import fiona; help(fiona.open)``
     """
     bbox = kwargs.pop('bbox', None)
@@ -27,6 +27,10 @@ def read_file(filename, **kwargs):
             f_filt = f
         gdf = GeoDataFrame.from_features(f_filt, crs=crs)
 
+        # re-order with column order from metadata, with geometry last
+        columns = list(f.meta["schema"]["properties"]) + ["geometry"]
+        gdf = gdf[columns]
+
     return gdf
 
 


Test patch:
diff --git a/geopandas/io/tests/test_io.py b/geopandas/io/tests/test_io.py
--- a/geopandas/io/tests/test_io.py
+++ b/geopandas/io/tests/test_io.py
@@ -14,6 +14,7 @@ def setUp(self):
         self.df = read_file(nybb_zip_path, vfs=vfs)
         with fiona.open(nybb_zip_path, vfs=vfs) as f:
             self.crs = f.crs
+            self.columns = list(f.meta["schema"]["properties"].keys())
 
     def test_read_postgis_default(self):
         con = connect('test_geopandas')
@@ -54,6 +55,9 @@ def test_read_file(self):
         df = self.df.rename(columns=lambda x: x.lower())
         validate_boro_df(self, df)
         self.assert_(df.crs == self.crs)
+        # get lower case columns, and exclude geometry column from comparison
+        lower_columns = [c.lower() for c in self.columns]
+        self.assert_((df.columns[:-1] == lower_columns).all())
 
     def test_filtered_read_file(self):
         full_df_shape = self.df.shape
Repository: geopandas/geopandas

Issue:
BUG: coordinate indexer does not correctly handle slice start/stop of 0
When slicing a geoseries using the coordinate indexer, a slice start/stop of 0 is ignored.

```
>>> gs = gpd.GeoSeries([Point(x, x) for x in range(-3, 4)])
>>> print(gs)
0    POINT (-3 -3)
1    POINT (-2 -2)
2    POINT (-1 -1)
3      POINT (0 0)
4      POINT (1 1)
5      POINT (2 2)
6      POINT (3 3)
dtype: object
```
When attempting to select points located with x/y < 0, you get:
```
>>> print(gs.cx[:0, :0])
0    POINT (-3 -3)
1    POINT (-2 -2)
2    POINT (-1 -1)
3      POINT (0 0)
4      POINT (1 1)
5      POINT (2 2)
6      POINT (3 3)
dtype: object
```
whereas the expected behavior is:
```
>>> print(gs.cx[:0, :0])
0    POINT (-3 -3)
1    POINT (-2 -2)
2    POINT (-1 -1)
3      POINT (0 0)
```


Discussion:

Resolving patch:
diff --git a/geopandas/geoseries.py b/geopandas/geoseries.py
--- a/geopandas/geoseries.py
+++ b/geopandas/geoseries.py
@@ -37,10 +37,10 @@ def _getitem_tuple(self, tup):
         if xs.step is not None or ys.step is not None:
             warn("Ignoring step - full interval is used.")
         xmin, ymin, xmax, ymax = obj.total_bounds
-        bbox = box(xs.start or xmin,
-                   ys.start or ymin,
-                   xs.stop or xmax,
-                   ys.stop or ymax)
+        bbox = box(xs.start if xs.start is not None else xmin,
+                   ys.start if ys.start is not None else ymin,
+                   xs.stop if xs.stop is not None else xmax,
+                   ys.stop if ys.stop is not None else ymax)
         idx = obj.intersects(bbox)
         return obj[idx]
 


Test patch:
diff --git a/geopandas/tests/test_geoseries.py b/geopandas/tests/test_geoseries.py
--- a/geopandas/tests/test_geoseries.py
+++ b/geopandas/tests/test_geoseries.py
@@ -152,6 +152,17 @@ def test_coord_slice(self):
         self.assertTrue(geom_equals(self.g3[[True, False]], self.g3.cx[0.9:, :0.1]))
         self.assertTrue(geom_equals(self.g3[[False, True]], self.g3.cx[0:0.1, 0.9:1.0]))
 
+    def test_coord_slice_with_zero(self):
+        # Test that CoordinateSlice correctly handles zero slice (#GH477).
+
+        gs = GeoSeries([Point(x, x) for x in range(-3, 4)])
+        self.assertTrue(geom_equals(gs.cx[:0, :0], gs.loc[:3]))
+        self.assertTrue(geom_equals(gs.cx[:, :0], gs.loc[:3]))
+        self.assertTrue(geom_equals(gs.cx[:0, :], gs.loc[:3]))
+        self.assertTrue(geom_equals(gs.cx[0:, 0:], gs.loc[3:]))
+        self.assertTrue(geom_equals(gs.cx[0:, :], gs.loc[3:]))
+        self.assertTrue(geom_equals(gs.cx[:, 0:], gs.loc[3:]))
+
     def test_geoseries_geointerface(self):
         self.assertEqual(self.g1.__geo_interface__['type'], 'FeatureCollection')
         self.assertEqual(len(self.g1.__geo_interface__['features']),
Repository: geopandas/geopandas

Issue:
BUG/COMPAT: missing values handling / fillna no longer working with shapely 1.6
See https://github.com/Toblerity/Shapely/issues/510 for more detailed exploration of the problem

Temporarily pinned our CI to older shapely version (but kept one with the latest shapely in the allowed failures section) in https://github.com/geopandas/geopandas/pull/508


Discussion:
So we should fix this for 0.3. 
This pops up when you have missing values in the geometry column. Filling the missing values with an empty geometry no longer works. Therefore you get an error "" AttributeError: 'NoneType' object has no attribute 'is_empty' "", because in the operations, we often check if a geom is empty or not before performing the op, eg:

https://github.com/geopandas/geopandas/blob/6dc4ab2cc9f7a6cdffa9d33c8300ff734410a448/geopandas/base.py#L51

So either we also check for nan/None in the above check, or we fix the fillna. To fix fillna, we probably have to broadcast the fill value (empty geometry) to a like-indexed series ourselfves (as it is this step with numpy in the pandas internals that no longer works due to changes in the array interface of empty polygons)


Resolving patch:
diff --git a/geopandas/geoseries.py b/geopandas/geoseries.py
--- a/geopandas/geoseries.py
+++ b/geopandas/geoseries.py
@@ -184,14 +184,14 @@ def fillna(self, value=None, method=None, inplace=False,
         "method" is currently not implemented for pandas <= 0.12.
         """
         if value is None:
-            value = Point()
+            value = BaseGeometry()
         return super(GeoSeries, self).fillna(value=value, method=method,
                                              inplace=inplace, **kwargs)
 
     def align(self, other, join='outer', level=None, copy=True,
               fill_value=None, **kwargs):
         if fill_value is None:
-            fill_value = Point()
+            fill_value = BaseGeometry()
         left, right = super(GeoSeries, self).align(other, join=join,
                                                    level=level, copy=copy,
                                                    fill_value=fill_value,


Test patch:
diff --git a/geopandas/tests/test_geoseries.py b/geopandas/tests/test_geoseries.py
--- a/geopandas/tests/test_geoseries.py
+++ b/geopandas/tests/test_geoseries.py
@@ -152,7 +152,8 @@ def test_transform(self):
             self.landmarks.to_crs(crs=None, epsg=None)
 
     def test_fillna(self):
-        na = self.na_none.fillna(Point())
+        # default is to fill with empty geometry
+        na = self.na_none.fillna()
         assert isinstance(na[2], BaseGeometry)
         assert na[2].is_empty
         assert geom_equals(self.na_none[:2], na[:2])
Repository: geopandas/geopandas

Issue:
ENH: passthrough additional kwargs for buffer
The shapely `buffer` method has some more options (see https://shapely.readthedocs.io/en/latest/manual.html#object.buffer), we could pass them through


Discussion:

Resolving patch:
diff --git a/geopandas/base.py b/geopandas/base.py
--- a/geopandas/base.py
+++ b/geopandas/base.py
@@ -295,8 +295,8 @@ def sindex(self):
             self._generate_sindex()
         return self._sindex
 
-    def buffer(self, distance, resolution=16):
-        return gpd.GeoSeries([geom.buffer(distance, resolution)
+    def buffer(self, distance, resolution=16, **kwargs):
+        return gpd.GeoSeries([geom.buffer(distance, resolution, **kwargs)
                              for geom in self.geometry],
                          index=self.index, crs=self.crs)
 


Test patch:
diff --git a/geopandas/tests/test_geom_methods.py b/geopandas/tests/test_geom_methods.py
--- a/geopandas/tests/test_geom_methods.py
+++ b/geopandas/tests/test_geom_methods.py
@@ -423,6 +423,20 @@ def test_skew(self):
         res = res.skew(ys=-skew, origin=o)
         assert geom_almost_equals(expected, res)
 
+    def test_buffer(self):
+        original = GeoSeries([Point(0, 0)])
+        expected = GeoSeries([Polygon(((5, 0), (0, -5), (-5, 0), (0, 5),
+                                       (5, 0)))])
+        calculated = original.buffer(5, resolution=1)
+        assert geom_almost_equals(expected, calculated)
+
+    def test_buffer_args(self):
+        args = dict(cap_style=3, join_style=2, mitre_limit=2.5)
+        calculated_series = self.g0.buffer(10, **args)
+        for original, calculated in zip(self.g0, calculated_series):
+            expected = original.buffer(10, **args)
+            assert calculated.equals(expected)
+
     def test_envelope(self):
         e = self.g3.envelope
         assert np.all(e.geom_equals(self.sq))
Repository: geopandas/geopandas

Issue:
Descartes dependency
In the docs, geopandas lists descartes and matplotlib as optional dependencies. However, descartes is listed as an install_requires in the setup.py.

One of the two should be updated. I'd prefer to be able to pip install geopandas without installing matplotlib.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -29,7 +29,7 @@
 if os.environ.get('READTHEDOCS', False) == 'True':
     INSTALL_REQUIRES = []
 else:
-    INSTALL_REQUIRES = ['pandas', 'shapely', 'fiona', 'descartes', 'pyproj']
+    INSTALL_REQUIRES = ['pandas', 'shapely', 'fiona', 'pyproj']
 
 # get all data dirs in the datasets module
 data_files = []


Test patch:
Repository: geopandas/geopandas

Issue:
Raise error when trying to write empty dataframes
Currently, the behavior when writing an empty dataframe is counter-intuitive (`ValueError: Geometry column cannot contain mutiple geometry types when writing to file.`). Would it be possible to add  a check and more helpful exception?  


Discussion:
Yes, that should not be difficult to raise a more informative error message. The current check happens here: https://github.com/geopandas/geopandas/blob/master/geopandas/io/file.py#L134. We could add a check that checks for `if df.empty: ...`. 
PR welcome!

@jorisvandenbossche I can take this, if needed!
That's certainly welcome!

Resolving patch:
diff --git a/geopandas/io/file.py b/geopandas/io/file.py
--- a/geopandas/io/file.py
+++ b/geopandas/io/file.py
@@ -130,7 +130,11 @@ def convert_type(column, in_type):
         zip(df.columns, df.dtypes) if col != df._geometry_column_name
     ])
 
+    if df.empty:
+        raise ValueError("Cannot write empty DataFrame to file.")
+
     geom_type = _common_geom_type(df)
+    
     if not geom_type:
         raise ValueError("Geometry column cannot contain mutiple "
                          "geometry types when writing to file.")


Test patch:
diff --git a/geopandas/tests/test_geodataframe.py b/geopandas/tests/test_geodataframe.py
--- a/geopandas/tests/test_geodataframe.py
+++ b/geopandas/tests/test_geodataframe.py
@@ -361,6 +361,13 @@ def test_mixed_types_to_file(self):
         with pytest.raises(ValueError):
             s.to_file(tempfilename)
 
+    def test_empty_to_file(self):
+        input_empty_df = GeoDataFrame()
+        tempfilename = os.path.join(self.tempdir, 'test.shp')
+        with pytest.raises(
+            ValueError, match="Cannot write empty DataFrame to file."):
+            input_empty_df.to_file(tempfilename)
+
     def test_to_file_schema(self):
         """
         Ensure that the file is written according to the schema
Repository: geopandas/geopandas

Issue:
Import error: `descartes` removed?
testing a plot dependent on `geopandas`:
Is seems like `descartes` was removed. 

```  
File "/home/travis/build/pysal/esda/miniconda/envs/test-env/lib/python3.5/site-packages/geopandas/geodataframe.py", line 534, in plot
    return plot_dataframe(self, *args, **kwargs)
File "/home/travis/build/pysal/esda/miniconda/envs/test-env/lib/python3.5/site-packages/geopandas/plotting.py", line 451, in plot_dataframe
    vmin=mn, vmax=mx, cmap=cmap, **style_kwds)
File "/home/travis/build/pysal/esda/miniconda/envs/test-env/lib/python3.5/site-packages/geopandas/plotting.py", line 80, in plot_polygon_collection
    from descartes.patch import PolygonPatch
ImportError: No module named 'descartes'
```

@ljwolf 


Discussion:

Resolving patch:
diff --git a/geopandas/plotting.py b/geopandas/plotting.py
--- a/geopandas/plotting.py
+++ b/geopandas/plotting.py
@@ -77,7 +77,12 @@ def plot_polygon_collection(ax, geoms, values=None, color=None,
 
     collection : matplotlib.collections.Collection that was plotted
     """
-    from descartes.patch import PolygonPatch
+
+    try:
+        from descartes.patch import PolygonPatch
+    except ImportError:
+        raise ImportError("The descartes package is required"
+                          " for plotting polygons in geopandas.")
     from matplotlib.collections import PatchCollection
 
     geoms, values = _flatten_multi_geoms(geoms, values)


Test patch:
Repository: geopandas/geopandas

Issue:
VIS/PERF: only flatten geometries when there are actually multi-geometries
Currently we always loop through all geometries in `_flatten_multi_geoms` when plotting geometries, even when there are no Multi-Point/LineString/Polygons. 

A check in advance if there are multi-geometries, and thus to know whether the flattening is needed, would increase the performance of the plotting of many single geometries.


Discussion:

Resolving patch:
diff --git a/geopandas/plotting.py b/geopandas/plotting.py
--- a/geopandas/plotting.py
+++ b/geopandas/plotting.py
@@ -26,6 +26,9 @@ def _flatten_multi_geoms(geoms, colors=None):
         colors = [None] * len(geoms)
 
     components, component_colors = [], []
+    
+    if not geoms.geom_type.str.startswith('Multi').any():
+        return geoms, colors
 
     # precondition, so zip can't short-circuit
     assert len(geoms) == len(colors)


Test patch:
Repository: geopandas/geopandas

Issue:
Deprecation Warning with fiona 1.8b1
using a `debian:buster` docker image

installed Fiona with 
> pip install git+https://github.com/Toblerity/Fiona.git@1.8b1

I got this __warning__ today: 
```python
/usr/local/lib/python2.7/dist-packages/geopandas/io/file.py:108: FionaDeprecationWarning: Use fiona.Env() instead.
  with fiona.drivers():
No handlers could be found for logger "rasterio._gdal"
```


Discussion:
@vesnikos Thanks for the report! 
I was also just testing Fiona 1.8 (https://github.com/geopandas/geopandas/pull/844, https://github.com/Toblerity/Fiona/issues/647), and saw the same. So we will have to update our code to use `Env` instead (depending on the fiona version). 


PRs always welcome!

Resolving patch:
diff --git a/geopandas/io/file.py b/geopandas/io/file.py
--- a/geopandas/io/file.py
+++ b/geopandas/io/file.py
@@ -4,6 +4,11 @@
 import numpy as np
 import six
 
+try:
+    from fiona import Env as fiona_env
+except ImportError:
+    from fiona import drivers as fiona_env
+
 from geopandas import GeoDataFrame, GeoSeries
 
 # Adapted from pandas.io.common
@@ -105,7 +110,7 @@ def to_file(df, filename, driver="ESRI Shapefile", schema=None,
     if schema is None:
         schema = infer_schema(df)
     filename = os.path.abspath(os.path.expanduser(filename))
-    with fiona.drivers():
+    with fiona_env():
         with fiona.open(filename, 'w', driver=driver, crs=df.crs,
                         schema=schema, **kwargs) as colxn:
             colxn.writerecords(df.iterfeatures())


Test patch:
diff --git a/geopandas/io/tests/test_io.py b/geopandas/io/tests/test_io.py
--- a/geopandas/io/tests/test_io.py
+++ b/geopandas/io/tests/test_io.py
@@ -8,6 +8,7 @@
 
 import geopandas
 from geopandas import read_postgis, read_file
+from geopandas.io.file import fiona_env
 from geopandas.tests.util import connect, create_postgis, validate_boro_df
 
 
@@ -172,7 +173,7 @@ def test_empty_shapefile(self, tmpdir):
 
         fname = str(tmpdir.join("test_empty.shp"))
 
-        with fiona.drivers():
+        with fiona_env():
             with fiona.open(fname, 'w', **meta) as _:
                 pass
Repository: geopandas/geopandas

Issue:
BUG: GeoDataFrame.astype(..) does not return a GeoDataFrame when possible
Using the `astype` method on a GeoDataFrame, looses the subclass and returns a plain DataFrame:

```
In [1]: import geopandas

In [2]: df = geopandas.read_file(geopandas.datasets.get_path('nybb')) 

In [3]: type(df)          
Out[3]: geopandas.geodataframe.GeoDataFrame

In [4]: df2 = df.astype({'BoroCode': str}) 

In [5]: type(df2)       
Out[5]: pandas.core.frame.DataFrame
```

One could argue that this is a bug in pandas (and can also probably solved in pandas), but on the short term, we can solve that by overriding `astype` in the GeoDataFrame class.


Discussion:
`astype` is in the class definition for `pandas.core.generic.NDFrame` which is a superclass of `pandas.DataFrame`. What makes you think this might be a bug in pandas? The conversion seems to be done correctly:

```
df.astype({'BoroCode': str})['BoroCode'].values
array(['5', '4', '3', '1', '2'], dtype=object)
df['BoroCode'].values
array([5, 4, 3, 1, 2], dtype=int64)
```


Resolving patch:
diff --git a/geopandas/geodataframe.py b/geopandas/geodataframe.py
--- a/geopandas/geodataframe.py
+++ b/geopandas/geodataframe.py
@@ -691,6 +691,29 @@ def explode(self):
         geo_df = df.set_geometry(self._geometry_column_name)
         return geo_df
 
+    # overrides the pandas astype method to ensure the correct return type
+    def astype(self, dtype, copy=True, errors="raise", **kwargs):
+        """
+        Cast a pandas object to a specified dtype ``dtype``.
+
+        Returns a GeoDataFrame when the geometry column is kept as geometries,
+        otherwise returns a pandas DataFrame.
+
+        See the pandas.DataFrame.astype docstring for more details.
+
+        Returns
+        -------
+        GeoDataFrame or DataFrame
+        """
+        df = super(GeoDataFrame, self).astype(dtype, copy=copy, errors=errors, **kwargs)
+
+        try:
+            df = geopandas.GeoDataFrame(df, geometry=self._geometry_column_name)
+            return df
+        except TypeError:
+            df = pd.DataFrame(df)
+            return df
+
 
 def _dataframe_set_geometry(self, col, drop=False, inplace=False, crs=None):
     if inplace:


Test patch:
diff --git a/geopandas/tests/test_pandas_methods.py b/geopandas/tests/test_pandas_methods.py
--- a/geopandas/tests/test_pandas_methods.py
+++ b/geopandas/tests/test_pandas_methods.py
@@ -129,13 +129,27 @@ def test_assign(df):
     assert_frame_equal(res, exp)
 
 
-def test_astype(s):
+def test_astype(s, df):
 
+    # check geoseries functionality
     with pytest.raises(TypeError):
         s.astype(int)
 
     assert s.astype(str)[0] == "POINT (0 0)"
 
+    df = df.rename_geometry("geom_list")
+
+    # check whether returned object is a geodataframe
+    df = df.astype({"value1": float})
+    assert isinstance(df, GeoDataFrame)
+
+    # check whether returned object is a datafrane
+    df = df.astype(str)
+    assert isinstance(df, pd.DataFrame)
+
+    df = df.astype({"geom_list": str})
+    assert isinstance(df, pd.DataFrame)
+
 
 def test_to_csv(df):
Repository: geopandas/geopandas

Issue:
Pull `mapclassify` from `pysal`
Currently, if the user wants to make a choropleth, `geopandas` requires `mapclassify`, part of the `pysal` family. This is convenient because it allows `geopandas` to install only the classifiers and avoid, if the user wants, all the other libraries. However, if a user has installed a full `pysal` version (e.g. 2.1), but not classify, `geopandas.plot(scheme=)` will fail as it will not find an independent version of mapclassify. Would it be possible to make an extra check (maybe [here](https://github.com/geopandas/geopandas/blob/master/geopandas/plotting.py#L557)) to see if `import mapclassify` fails, whether `import pysal.viz.mapclassify` works? That'd avoid duplicating an install on the user's system.


Discussion:
So if you install pysal, it does *not* install the separate packages? (I assumed it would, and it then imports that package if you access `pysal.viz.mapclassify`)
@jorisvandenbossche `pysal` currently duplicates the code base in this case. It has everything within `pysal` package and then parts of it are also released separately, like `mapclassify` or `libpysal`. So with this design, it makes sense for `geopandas` to check for both. However, I agree with you that having it vice versa (load packages to `pysal`) would make much more sense.

Resolving patch:
diff --git a/geopandas/plotting.py b/geopandas/plotting.py
--- a/geopandas/plotting.py
+++ b/geopandas/plotting.py
@@ -555,15 +555,18 @@ class identifier and the bins.
 
     """
     try:
-        import mapclassify.classifiers
+        import mapclassify.classifiers as classifiers
     except ImportError:
-        raise ImportError(
-            "The 'mapclassify' package is required to use the 'scheme' "
-            "keyword")
+        try:
+            import pysal.viz.mapclassify.classifiers as classifiers
+        except ImportError:
+            raise ImportError(
+                "The 'mapclassify' or 'pysal' package is required to use the"
+                " 'scheme' keyword")
 
     schemes = {}
-    for classifier in mapclassify.classifiers.CLASSIFIERS:
-        schemes[classifier.lower()] = getattr(mapclassify.classifiers,
+    for classifier in classifiers.CLASSIFIERS:
+        schemes[classifier.lower()] = getattr(classifiers,
                                               classifier)
 
     scheme = scheme.lower()


Test patch:
diff --git a/geopandas/tests/test_plotting.py b/geopandas/tests/test_plotting.py
--- a/geopandas/tests/test_plotting.py
+++ b/geopandas/tests/test_plotting.py
@@ -402,7 +402,13 @@ class TestMapclassifyPlotting:
 
     @classmethod
     def setup_class(cls):
-        pytest.importorskip('mapclassify')
+        try:
+            import mapclassify
+        except ImportError:
+            try:
+                import pysal
+            except ImportError:
+                pytest.importorskip('mapclassify')
         pth = get_path('naturalearth_lowres')
         cls.df = read_file(pth)
         cls.df['NEGATIVES'] = np.linspace(-10, 10, len(cls.df.index))