Repository: pydata/xarray

Issue:
Problem using swap_dims with datetime coordinate for xarray 0.12.0
#### Code Sample, a copy-pastable example if possible

```python
import datetime as dt 
import xarray as xr
df =  xr.Dataset({'day': [1,2],
                  'date':('day',[dt.datetime(2018,1,2),dt.datetime(2018,1,3)]),
                  "var": ('day', [ 5,6])})
print(df.indexes)
df_d=df.swap_dims({"day":"date"}).swap_dims({"date":"day"})
print(df_d.indexes)
```
#### Problem description

When changing coordinate from **integer to datetime to integer** the indexes are still  datetime object with version 0.12.0 while I expect Integer (as in version 0.11.3). 
Indeed I get the following results :  

day: Int64Index([1, 2], dtype='int64', name='day')
day: DatetimeIndex(['2018-01-02', '2018-01-03'], dtype='datetime64[ns]', name='day', freq=None)
 

#### Expected Output
With previous version of xarray I get  the expected output. 

day: Int64Index([1, 2], dtype='int64', name='day')
day: Int64Index([1, 2], dtype='int64', name='day')

#### Output of ``xr.show_versions()``

<details>
INSTALLED VERSIONS
------------------

commit: None
python: 3.6.7 | packaged by conda-forge | (default, Feb 20 2019, 02:51:38) 
[GCC 7.3.0]
python-bits: 64
OS: Linux
OS-release: 4.9.0-8-amd64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8
libhdf5: 1.10.4
libnetcdf: 4.6.2

xarray: 0.12.0
pandas: 0.24.2
numpy: 1.15.4
scipy: 1.2.1
netCDF4: 1.4.3.2
pydap: None
h5netcdf: None
h5py: 2.9.0
Nio: 1.5.5
zarr: None
cftime: 1.0.3.4
nc_time_axis: None
PseudonetCDF: None
rasterio: 1.0.22
cfgrib: None
iris: 2.2.0
bottleneck: None
dask: 1.1.4
distributed: 1.26.0
matplotlib: 3.0.3
cartopy: 0.17.0
seaborn: 0.9.0
setuptools: 40.8.0
pip: 19.0.3
conda: 4.6.8
pytest: 4.3.1
IPython: 7.3.0
sphinx: None
</details>


#### Output of  previous ``xr.show_versions()``
<details>
INSTALLED VERSIONS
------------------

commit: None
python: 3.6.7 | packaged by conda-forge | (default, Feb 20 2019, 02:51:38) 
[GCC 7.3.0]
python-bits: 64
OS: Linux
OS-release: 4.9.0-8-amd64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8
libhdf5: 1.10.4
libnetcdf: 4.6.2

xarray: 0.11.3
pandas: 0.24.2
numpy: 1.15.4
scipy: 1.2.1
netCDF4: 1.4.3.2
pydap: None
h5netcdf: None
h5py: 2.9.0
Nio: 1.5.5
zarr: None
cftime: 1.0.3.4
PseudonetCDF: None
rasterio: 1.0.21
cfgrib: None
iris: 2.2.0
bottleneck: None
cyordereddict: None
dask: 1.1.4
distributed: 1.26.0
matplotlib: 3.0.2
cartopy: 0.17.0
seaborn: 0.9.0
setuptools: 40.8.0
pip: 19.0.3
conda: 4.6.8
pytest: 4.3.1
IPython: 7.3.0
sphinx: None
</details>

Discussion:

Patch:
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index 3de610b3..6cf2720a 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -25,6 +25,9 @@ Enhancements
 Bug fixes
 ~~~~~~~~~
 
+- ``swap_dims`` would create incorrect ``indexes`` (:issue:`2842`).
+  By `Stephan Hoyer <https://github.com/shoyer>`_.
+
 
 .. _whats-new.0.12.0:
 
diff --git a/xarray/backends/api.py b/xarray/backends/api.py
index a982c6cd..afb69f6e 100644
--- a/xarray/backends/api.py
+++ b/xarray/backends/api.py
@@ -230,7 +230,7 @@ def open_dataset(filename_or_obj, group=None, decode_cf=True,
     decode_coords : bool, optional
         If True, decode the 'coordinates' attribute to identify coordinates in
         the resulting dataset.
-    engine : {'netcdf4', 'scipy', 'pydap', 'h5netcdf', 'pynio', 'cfgrib',
+    engine : {'netcdf4', 'scipy', 'pydap', 'h5netcdf', 'pynio', 'cfgrib', \
         'pseudonetcdf'}, optional
         Engine to use when reading files. If not provided, the default engine
         is chosen based on available dependencies, with a preference for
@@ -445,7 +445,7 @@ def open_dataarray(filename_or_obj, group=None, decode_cf=True,
     decode_coords : bool, optional
         If True, decode the 'coordinates' attribute to identify coordinates in
         the resulting dataset.
-    engine : {'netcdf4', 'scipy', 'pydap', 'h5netcdf', 'pynio', 'cfgrib'},
+    engine : {'netcdf4', 'scipy', 'pydap', 'h5netcdf', 'pynio', 'cfgrib'}, \
         optional
         Engine to use when reading files. If not provided, the default engine
         is chosen based on available dependencies, with a preference for
@@ -584,7 +584,7 @@ def open_mfdataset(paths, chunks=None, concat_dim=_CONCAT_DIM_DEFAULT,
         If provided, call this function on each dataset prior to concatenation.
         You can find the file-name from which each dataset was loaded in
         ``ds.encoding['source']``.
-    engine : {'netcdf4', 'scipy', 'pydap', 'h5netcdf', 'pynio', 'cfgrib'},
+    engine : {'netcdf4', 'scipy', 'pydap', 'h5netcdf', 'pynio', 'cfgrib'}, \
         optional
         Engine to use when reading files. If not provided, the default engine
         is chosen based on available dependencies, with a preference for
diff --git a/xarray/backends/lru_cache.py b/xarray/backends/lru_cache.py
index e407c384..4be6efea 100644
--- a/xarray/backends/lru_cache.py
+++ b/xarray/backends/lru_cache.py
@@ -1,8 +1,9 @@
 import collections
+import collections.abc
 import threading
 
 
-class LRUCache(collections.MutableMapping):
+class LRUCache(collections.abc.MutableMapping):
     """Thread-safe LRUCache based on an OrderedDict.
 
     All dict operations (__getitem__, __setitem__, __contains__) update the
diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py
index 3463ada6..3bb54e80 100644
--- a/xarray/core/dataset.py
+++ b/xarray/core/dataset.py
@@ -2307,24 +2307,20 @@ class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords):
         coord_names.update(dims_dict.values())
 
         variables = OrderedDict()
+        indexes = OrderedDict()
         for k, v in self.variables.items():
             dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
             if k in result_dims:
                 var = v.to_index_variable()
+                if k in self.indexes:
+                    indexes[k] = self.indexes[k]
+                else:
+                    indexes[k] = var.to_index()
             else:
                 var = v.to_base_variable()
             var.dims = dims
             variables[k] = var
 
-        indexes = OrderedDict()
-        for k, v in self.indexes.items():
-            if k in dims_dict:
-                new_name = dims_dict[k]
-                new_index = variables[k].to_index()
-                indexes[new_name] = new_index
-            else:
-                indexes[k] = v
-
         return self._replace_with_new_dims(variables, coord_names,
                                            indexes=indexes, inplace=inplace)
 


Test patch:
diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py
index 8e8c6c4b..777a8e84 100644
--- a/xarray/tests/test_dataset.py
+++ b/xarray/tests/test_dataset.py
@@ -2002,14 +2002,11 @@ class TestDataset(object):
         assert_identical(expected, actual)
         assert isinstance(actual.variables['y'], IndexVariable)
         assert isinstance(actual.variables['x'], Variable)
+        assert actual.indexes['y'].equals(pd.Index(list('abc')))
 
         roundtripped = actual.swap_dims({'y': 'x'})
         assert_identical(original.set_coords('y'), roundtripped)
 
-        actual = original.copy()
-        actual = actual.swap_dims({'x': 'y'})
-        assert_identical(expected, actual)
-
         with raises_regex(ValueError, 'cannot swap'):
             original.swap_dims({'y': 'x'})
         with raises_regex(ValueError, 'replacement dimension'):