Repository: pydata/xarray

Issue:
xr.concat adds an extra array around elements
### What happened?

When concatenating dataarrays with `pd.Interval` along a dim the `pd.Interval` is wrapped with a numpy array and appended  instead of without like it it was before #5692.

### Minimal Complete Verifiable Example

```Python
import numpy as np
import xarray as xr

shape = (2, 3, 4)
darray = xr.DataArray(np.linspace(0, 1, num=np.prod(shape)).reshape(shape))
bins = [-1, 0, 1, 2]
a = darray.groupby_bins("dim_0", bins).mean(...)
a_nan = np.nan * a.isel(**{"dim_0_bins": -1})
out = xr.concat([a, a_nan], dim="dim_0_bins")
print(out["dim_0_bins"])
```


### Relevant log output
Current result:
```Python
<xarray.DataArray 'dim_0_bins' (dim_0_bins: 4)>
array([Interval(-1, 0, closed='right'), Interval(0, 1, closed='right'),
       Interval(1, 2, closed='right'),
       array(Interval(1, 2, closed='right'), dtype=object)], dtype=object)
Coordinates:
  * dim_0_bins  (dim_0_bins) object (-1, 0] (0, 1] (1, 2] (1, 2]
```

Should be:
```python
<xarray.DataArray 'dim_0_bins' (dim_0_bins: 4)>
array([Interval(-1, 0, closed='right'), Interval(0, 1, closed='right'),
       Interval(1, 2, closed='right'), Interval(1, 2, closed='right')],
      dtype=object)
Coordinates:
  * dim_0_bins  (dim_0_bins) object (-1, 0] (0, 1] (1, 2] (1, 2]

```
### Anything else we need to know?

_No response_

### Environment

<details>

xr.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.9.6 | packaged by conda-forge | (default, Jul 11 2021, 03:37:25) [MSC v.1916 64 bit (AMD64)]
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: en
LOCALE: ('Swedish_Sweden', '1252')
libhdf5: 1.10.6
libnetcdf: 4.7.4

xarray: 0.16.3.dev99+gc19467fb
pandas: 1.3.1
numpy: 1.21.5
scipy: 1.7.1
netCDF4: 1.5.6
pydap: installed
h5netcdf: 0.11.0
h5py: 2.10.0
Nio: None
zarr: 2.8.3
cftime: 1.5.0
nc_time_axis: 1.3.1
PseudoNetCDF: installed
rasterio: 1.2.6
cfgrib: None
iris: 3.0.4
bottleneck: 1.3.2
dask: 2021.10.0
distributed: 2021.10.0
matplotlib: 3.4.3
cartopy: 0.19.0.post1
seaborn: 0.11.1
numbagg: 0.2.1
fsspec: 2021.11.1
cupy: None
pint: 0.17
sparse: 0.12.0
setuptools: 49.6.0.post20210108
pip: 21.2.4
conda: None
pytest: 6.2.4
IPython: 7.31.0
sphinx: 4.3.2

</details>

Discussion:

Patch:
diff --git a/xarray/core/concat.py b/xarray/core/concat.py
index 8ee4672c..b23073e7 100644
--- a/xarray/core/concat.py
+++ b/xarray/core/concat.py
@@ -429,6 +429,7 @@ def _dataset_concat(
     """
     Concatenate a sequence of datasets along a new or existing dimension
     """
+    from .dataarray import DataArray
     from .dataset import Dataset
 
     datasets = list(datasets)
@@ -438,6 +439,13 @@ def _dataset_concat(
             "The elements in the input list need to be either all 'Dataset's or all 'DataArray's"
         )
 
+    if isinstance(dim, DataArray):
+        dim_var = dim.variable
+    elif isinstance(dim, Variable):
+        dim_var = dim
+    else:
+        dim_var = None
+
     dim, index = _calc_concat_dim_index(dim)
 
     # Make sure we're working on a copy (we'll be loading variables)
@@ -524,7 +532,7 @@ def _dataset_concat(
             elif name == dim:
                 var = ds._variables[name]
                 if not var.dims:
-                    yield PandasIndex([var.values], dim)
+                    yield PandasIndex([var.values.item()], dim)
 
     # stack up each variable and/or index to fill-out the dataset (in order)
     # n.b. this loop preserves variable order, needed for groupby.
@@ -582,7 +590,11 @@ def _dataset_concat(
 
     if index is not None:
         # add concat index / coordinate last to ensure that its in the final Dataset
-        result[dim] = index.create_variables()[dim]
+        if dim_var is not None:
+            index_vars = index.create_variables({dim: dim_var})
+        else:
+            index_vars = index.create_variables()
+        result[dim] = index_vars[dim]
         result_indexes[dim] = index
 
     # TODO: add indexes at Dataset creation (when it is supported)
diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py
index 155cf21b..37039490 100644
--- a/xarray/core/dataset.py
+++ b/xarray/core/dataset.py
@@ -2262,6 +2262,8 @@ class Dataset(DataWithCoords, DatasetReductions, DatasetArithmetic, Mapping):
                     new_var = var.isel(indexers=var_indexers)
                 else:
                     new_var = var.copy(deep=False)
+                if name not in indexes:
+                    new_var = new_var.to_base_variable()
             variables[name] = new_var
 
         coord_names = self._coord_names & variables.keys()
diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py
index 3c26c212..9212549d 100644
--- a/xarray/core/groupby.py
+++ b/xarray/core/groupby.py
@@ -996,7 +996,7 @@ class DatasetGroupByBase(GroupBy, DatasetGroupbyArithmetic):
         if coord is not None and dim not in applied_example.dims:
             index, index_vars = create_default_index_implicit(coord)
             indexes = {k: index for k in index_vars}
-            combined = combined._overwrite_indexes(indexes, variables=index_vars)
+            combined = combined._overwrite_indexes(indexes, index_vars)
         combined = self._maybe_restore_empty_groups(combined)
         combined = self._maybe_unstack(combined)
         return combined


Test patch:
diff --git a/xarray/tests/test_concat.py b/xarray/tests/test_concat.py
index 8abede64..f31b6972 100644
--- a/xarray/tests/test_concat.py
+++ b/xarray/tests/test_concat.py
@@ -440,6 +440,22 @@ class TestConcatDataset:
         expected = Dataset({"z": (("x", "y"), [[-1], [1]])}, {"x": [0, 1], "y": [0]})
         assert_identical(actual, expected)
 
+        # regression GH6384
+        objs = [
+            Dataset({}, {"x": pd.Interval(-1, 0, closed="right")}),
+            Dataset({"x": [pd.Interval(0, 1, closed="right")]}),
+        ]
+        actual = concat(objs, "x")
+        expected = Dataset(
+            {
+                "x": [
+                    pd.Interval(-1, 0, closed="right"),
+                    pd.Interval(0, 1, closed="right"),
+                ]
+            }
+        )
+        assert_identical(actual, expected)
+
     def test_concat_do_not_promote(self) -> None:
         # GH438
         objs = [
@@ -459,8 +475,15 @@ class TestConcatDataset:
 
     def test_concat_dim_is_variable(self) -> None:
         objs = [Dataset({"x": 0}), Dataset({"x": 1})]
-        coord = Variable("y", [3, 4])
-        expected = Dataset({"x": ("y", [0, 1]), "y": [3, 4]})
+        coord = Variable("y", [3, 4], attrs={"foo": "bar"})
+        expected = Dataset({"x": ("y", [0, 1]), "y": coord})
+        actual = concat(objs, coord)
+        assert_identical(actual, expected)
+
+    def test_concat_dim_is_dataarray(self) -> None:
+        objs = [Dataset({"x": 0}), Dataset({"x": 1})]
+        coord = DataArray([3, 4], dims="y", attrs={"foo": "bar"})
+        expected = Dataset({"x": ("y", [0, 1]), "y": coord})
         actual = concat(objs, coord)
         assert_identical(actual, expected)
 
diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py
index 96fa4ef1..fe9ec56f 100644
--- a/xarray/tests/test_dataset.py
+++ b/xarray/tests/test_dataset.py
@@ -1262,6 +1262,15 @@ class TestDataset:
         with pytest.raises(IndexError, match=r"dimension coordinate 'dim2'"):
             actual = data.isel(dim2=indexing_ds["dim2"])
 
+    def test_isel_fancy_convert_index_variable(self) -> None:
+        # select index variable "x" with a DataArray of dim "z"
+        # -> drop index and convert index variable to base variable
+        ds = xr.Dataset({"foo": ("x", [1, 2, 3])}, coords={"x": [0, 1, 2]})
+        idxr = xr.DataArray([1], dims="z", name="x")
+        actual = ds.isel(x=idxr)
+        assert "x" not in actual.xindexes
+        assert not isinstance(actual.x.variable, IndexVariable)
+
     def test_sel(self):
         data = create_test_data()
         int_slicers = {"dim1": slice(None, None, 2), "dim2": slice(2), "dim3": slice(3)}
diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py
index f866b68d..327c8d34 100644
--- a/xarray/tests/test_groupby.py
+++ b/xarray/tests/test_groupby.py
@@ -934,6 +934,14 @@ def test_groupby_dataset_assign():
     assert_identical(actual, expected)
 
 
+def test_groupby_dataset_map_dataarray_func():
+    # regression GH6379
+    ds = xr.Dataset({"foo": ("x", [1, 2, 3, 4])}, coords={"x": [0, 0, 1, 1]})
+    actual = ds.groupby("x").map(lambda grp: grp.foo.mean())
+    expected = xr.DataArray([1.5, 3.5], coords={"x": [0, 1]}, dims="x", name="foo")
+    assert_identical(actual, expected)
+
+
 class TestDataArrayGroupBy:
     @pytest.fixture(autouse=True)
     def setup(self):