Skip to content

Commit 95d453c

Browse files
committed
add option to not create 1D index in expand_dims
1 parent 3e848eb commit 95d453c

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

xarray/core/dataset.py

+17-5
Original file line numberDiff line numberDiff line change
@@ -4479,6 +4479,7 @@ def expand_dims(
44794479
self,
44804480
dim: None | Hashable | Sequence[Hashable] | Mapping[Any, Any] = None,
44814481
axis: None | int | Sequence[int] = None,
4482+
create_1d_index: bool = True,
44824483
**dim_kwargs: Any,
44834484
) -> Self:
44844485
"""Return a new object with an additional axis (or axes) inserted at
@@ -4488,6 +4489,8 @@ def expand_dims(
44884489
If dim is already a scalar coordinate, it will be promoted to a 1D
44894490
coordinate consisting of a single value.
44904491
4492+
The
4493+
44914494
Parameters
44924495
----------
44934496
dim : hashable, sequence of hashable, mapping, or None
@@ -4503,6 +4506,8 @@ def expand_dims(
45034506
multiple axes are inserted. In this case, dim arguments should be
45044507
same length list. If axis=None is passed, all the axes will be
45054508
inserted to the start of the result array.
4509+
create_1d_index : bool, default is True
4510+
Whether to create new PandasIndex objects for new 1D coordinate variables.
45064511
**dim_kwargs : int or sequence or ndarray
45074512
The keywords are arbitrary dimensions being inserted and the values
45084513
are either the lengths of the new dims (if int is given), or their
@@ -4622,6 +4627,8 @@ def expand_dims(
46224627
# save the coordinates to the variables dict, and set the
46234628
# value within the dim dict to the length of the iterable
46244629
# for later use.
4630+
4631+
# TODO should we have an option to not create a variable here?
46254632
index = PandasIndex(v, k)
46264633
indexes[k] = index
46274634
variables.update(index.create_variables())
@@ -4660,11 +4667,16 @@ def expand_dims(
46604667
variables[k] = v.set_dims(dict(all_dims))
46614668
else:
46624669
if k not in variables:
4663-
# If dims includes a label of a non-dimension coordinate,
4664-
# it will be promoted to a 1D coordinate with a single value.
4665-
index, index_vars = create_default_index_implicit(v.set_dims(k))
4666-
indexes[k] = index
4667-
variables.update(index_vars)
4670+
if create_1d_index:
4671+
# If dims includes a label of a non-dimension coordinate,
4672+
# it will be promoted to a 1D coordinate with a single value.
4673+
index, index_vars = create_default_index_implicit(v.set_dims(k))
4674+
indexes[k] = index
4675+
variables.update(index_vars)
4676+
else:
4677+
# create 1D variable without creating a new index
4678+
new_1d_var = v.set_dims(k)
4679+
variables.update({k: new_1d_var})
46684680

46694681
return self._replace_with_new_dims(
46704682
variables, coord_names=coord_names, indexes=indexes

0 commit comments

Comments
 (0)