Repository: pydata/xarray

Issue:
Bug: side effect on method GroupBy.first  
#### Code Sample, a copy-pastable example if possible
```python
arr = xr.DataArray(
    np.arange(5), 
    dims=('x',), 
    coords={
        'x': ('x', np.array([1, 1, 1, 2, 2])),
    }
)

gr = arr.groupby('x')
gr.first()

arr

<xarray.DataArray (x: 5)>
array([0, 1, 2, 3, 4])
Coordinates:
  * x        (x) int64 1 2

```

#### Problem description
A side effect of the GroupBy.first method call is that it substitutes the original array coordinates with the grouped ones .

#### Expected Output
arr

<xarray.DataArray (x: 5)>
array([0, 1, 2, 3, 4])
Coordinates:
  * x        (x) int64 1 1 1 2 2

#### Output of ``xr.show_versions()``

<details>
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.0.final.0
python-bits: 64
OS: Linux
OS-release: 4.13.0-41-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

xarray: 0.10.4
pandas: 0.22.0
numpy: 1.14.3
scipy: 1.1.0
netCDF4: 1.3.1
h5netcdf: None
h5py: 2.7.1
Nio: None
zarr: None
bottleneck: None
cyordereddict: None
dask: 0.17.4
distributed: 1.21.8
matplotlib: 2.2.2
cartopy: 0.16.0
seaborn: None
setuptools: 38.4.1
pip: 10.0.1
conda: None
pytest: 3.5.1
IPython: 6.2.1
sphinx: 1.7.4

</details>


Discussion:

Patch:
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index f3af2b39..1465b9e6 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -82,6 +82,11 @@ Bug fixes
   the index) (:issue:`2165`).
   By `Spencer Clark <https://github.com/spencerkclark>`_.
 
+- Fix ``DataArray.groupby().reduce()`` mutating coordinates on the input array
+  when grouping over dimension coordinates with duplicated entries
+  (:issue:`2153`).
+  By `Stephan Hoyer <https://github.com/shoyer>`_
+  
 - Fix Dataset.to_netcdf() cannot create group with engine="h5netcdf"
   (:issue:`2177`).
   By `Stephan Hoyer <https://github.com/shoyer>`_
diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py
index 01f7c91f..fd2b49cc 100644
--- a/xarray/core/dataarray.py
+++ b/xarray/core/dataarray.py
@@ -252,7 +252,7 @@ class DataArray(AbstractArray, DataWithCoords):
 
     def _replace_maybe_drop_dims(self, variable, name=__default):
         if variable.dims == self.dims:
-            coords = None
+            coords = self._coords.copy()
         else:
             allowed_dims = set(variable.dims)
             coords = OrderedDict((k, v) for k, v in self._coords.items()


Test patch:
diff --git a/xarray/tests/test_computation.py b/xarray/tests/test_computation.py
index c829453c..bbcc02ba 100644
--- a/xarray/tests/test_computation.py
+++ b/xarray/tests/test_computation.py
@@ -553,7 +553,7 @@ def test_apply_dask():
     array = da.ones((2,), chunks=2)
     variable = xr.Variable('x', array)
     coords = xr.DataArray(variable).coords.variables
-    data_array = xr.DataArray(variable, coords, fastpath=True)
+    data_array = xr.DataArray(variable, dims=['x'], coords=coords)
     dataset = xr.Dataset({'y': variable})
 
     # encountered dask array, but did not set dask='allowed'
diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py
index fd53e410..6dd14f5d 100644
--- a/xarray/tests/test_groupby.py
+++ b/xarray/tests/test_groupby.py
@@ -5,6 +5,7 @@ import pandas as pd
 import pytest
 
 import xarray as xr
+from . import assert_identical
 from xarray.core.groupby import _consolidate_slices
 
 
@@ -73,4 +74,14 @@ def test_groupby_duplicate_coordinate_labels():
     assert expected.equals(actual)
 
 
+def test_groupby_input_mutation():
+    # regression test for GH2153
+    array = xr.DataArray([1, 2, 3], [('x', [2, 2, 1])])
+    array_copy = array.copy()
+    expected = xr.DataArray([3, 3], [('x', [1, 2])])
+    actual = array.groupby('x').sum()
+    assert_identical(expected, actual)
+    assert_identical(array, array_copy)  # should not modify inputs
+
+
 # TODO: move other groupby tests from test_dataset and test_dataarray over here