Skip to content

Commit 2db52f2

Browse files
committed
Allow pd.Index arguments as 'dim' in xray.concat
1 parent 92aeb43 commit 2db52f2

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

xray/core/dataset.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1341,11 +1341,20 @@ def concat(cls, *args, **kwargs):
13411341
@classmethod
13421342
def _concat(cls, datasets, dim='concat_dim', indexers=None,
13431343
mode='different', concat_over=None, compat='equals'):
1344+
from .dataarray import DataArray
1345+
13441346
_assert_compat_valid(compat)
13451347

13461348
# don't bother trying to work with datasets as a generator instead of a
13471349
# list; the gains would be minimal
13481350
datasets = list(map(as_dataset, datasets))
1351+
1352+
if not isinstance(dim, basestring) and not hasattr(dim, 'dims'):
1353+
# dim is not a DataArray or Coordinate
1354+
dim_name = getattr(dim, 'name', None)
1355+
if dim_name is None:
1356+
dim_name = 'concat_dim'
1357+
dim = DataArray(dim, dims=dim_name, name=dim_name)
13491358
dim_name = getattr(dim, 'name', dim)
13501359

13511360
# figure out variables to concatenate over

xray/test/test_dataarray.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -826,6 +826,17 @@ def test_concat(self):
826826
grouped = [g for _, g in foo.groupby('x')]
827827
stacked = concat(grouped, self.ds['x'])
828828
self.assertDataArrayIdentical(foo, stacked)
829+
# with an index as the 'dim' argument
830+
stacked = concat(grouped, self.ds.indexes['x'])
831+
self.assertDataArrayIdentical(foo, stacked)
832+
833+
actual = concat([foo[0], foo[1]], pd.Index([0, 1])).reset_coords(drop=True)
834+
expected = foo[:2].rename({'x': 'concat_dim'})
835+
self.assertDataArrayIdentical(expected, actual)
836+
837+
actual = concat([foo[0], foo[1]], [0, 1]).reset_coords(drop=True)
838+
expected = foo[:2].rename({'x': 'concat_dim'})
839+
self.assertDataArrayIdentical(expected, actual)
829840

830841
with self.assertRaisesRegexp(ValueError, 'not identical'):
831842
concat([foo, bar], compat='identical')

xray/test/test_dataset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -938,7 +938,7 @@ def rectify_dim_order(dataset):
938938
expected['dim1'] = dim
939939
self.assertDatasetIdentical(expected, concat(datasets, dim))
940940

941-
# TODO: factor this into several distinct tests
941+
def test_concat_errors(self):
942942
data = create_test_data()
943943
split_data = [data.isel(dim1=slice(10)),
944944
data.isel(dim1=slice(10, None))]

0 commit comments

Comments
 (0)